﻿using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reactive.Linq;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using DynamicData;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Win32;
using Serilog;
using SimpleTool.ActivityUnit.EchoControl;
using SimpleTool.Base;
using SimpleTool.Server;
using SimpleTool.TransformComponent;
using static SimpleTool.ActivityUnit.StalkerStepTemplate;
using static SimpleTool.Server.MesResportServer;

namespace SimpleTool.ActivityUnit
{
    public class ActivityViewModel : Notify
    {
        private readonly ILogger Logger = Log.ForContext<ActivityViewModel>();

        private readonly IPowerPlantServer PowerServer;

        private readonly IDataBaseServer DBServer;

        private readonly IDirFileServer IOServer;

        private readonly IDenCryptoGraphicServer CryptServer;

        private readonly IActivityDetetorServer ActivityServer;

        private readonly MesResportServer HoldMesResportServer;

        private ActivitySectionModel? ActivitySectionModelStdin = null;

        private MesargGroups? MesargGroupsStdin = null;

        private Deserted? DesertedOptionsStdin = null;

        private DateTimePush? DateTimePushStdin = null;

        private Argument? ArgumentOptionsStdin = null;

        private StalkerStepTemplate? StalkerStepTemplateStdin = null;

        private readonly ActivityDetetor ActivityDetetor;

        private Visibility VarbinPRegChildVisibleStdin = Visibility.Collapsed;

        private string MesargPushUrlStdin = string.Empty;

        private string VarbinRegProductContentStdin = string.Empty;

        private string VarbinRegProcessContentStdin = string.Empty;

        private string VarbinRegProductHintStdin = "关联主键";

        private string VarbinRegProcessHintStdin = "子健名称";

        private string VarbinRegChildKeyHintStdin = "是否子键";

        private string VarbinTestButtomTextStdin = "开始测试";

        private string VarbinProductTreeExtendTextStdin = "展开";

        private bool VarbinVsstStalkerStdin = false;

        private bool VarbinVsstMesFaceStdin = false;

        private bool VarbinVsstMesMapStdin = false;

        private UIBind VarbinUIBindStdin = new(Interfacial.PRDTProductOutTextBox);

        private double VarbinMenuOpacityStdin = 0;

        private int VarbinArgumentFaceSpanStsin = 1;

        private ICommand? CmdDBMapFileOpenStdin = null;

        private ICommand? CmdDBMapinfoSaveStdin = null;

        private ICommand? CmdDBMapuiExitStdin = null;

        private ICommand? CmdRegbindProductStdin = null;

        private ICommand? CmdRegbindProcessStdin = null;

        private ICommand? CmdRegAcceptStdin = null;

        private ICommand? CmdRegexitStdin = null;

        private ICommand? CmdRegchildSwitchStdin = null;

        private ICommand? CmdProductViewDeleteStdin = null;

        private ICommand? CmdProductViewUpdateStdin = null;

        private ICommand? CmdProductViewExitStdin = null;

        private ICommand? CmdTestStartStdin = null;

        private ICommand? CmdTopMenuMouseOverStdin = null;

        private ICommand? CmdConfigChoiceStdin = null;

        private ICommand? CmdProductChoiceStdin = null;

        private ICommand? CmdProductTreeStdin = null;

        private ICommand? CmdProductTreeExtendStdin = null;

        private ICommand? CmdClearSerialOutStdin = null;

        private ICommand? CmdMesDataBindingStdin = null;

        private ICommand? CmdAssistConfigOpenStdin = null;

        private ICommand? CmdStalkerStepShowStdin = null;

        private ICommand? CmdStalkerStepAddStdin = null;

        private ICommand? CmdStalkerStepBfAddStdin = null;

        private ICommand? CmdStalkerStepBfTakeStdin = null;

        private ICommand? CmdStalkerStepTakeStdin = null;

        private ICommand? CmdStalkerFlagChangeStdin = null;

        private ICommand? CmdTopMenuRegexpTestToolStdin = null;

        private ICommand? CmdTopMenuBitwiseXorToolStdin = null;

        private ICommand? CmdTopMenuTestStatisticalStdin = null;

        private ICommand? CmdTopMenuTestStatisticalFilterStdin = null;

        private ICommand? CmdTopMenuTestStatisticalCloseStdin = null;

        private ICommand? CmdCaptrueDeepSeatedStdin = null;

        private ICommand? CmdCaptrueDBMapConfigStdin = null;

        private ICommand? CmdCaptrueMesMapConfigStdin = null;

        private ICommand? CmdMesinfoMapExitStdin = null;

        private ICommand? CmdHyperlinkReceiveStdin = null;

        public string VarbinRegProductContent
        {
            set
            {
                VarbinRegProductContentStdin = value;
                propertyChangeSend(nameof(VarbinRegProductContent));
            }
            get
            {
                return VarbinRegProductContentStdin;
            }
        }

        public string VarbinRegProcessContent
        {
            set
            {
                VarbinRegProcessContentStdin = value;
                propertyChangeSend(nameof(VarbinRegProcessContent));
            }
            get
            {
                return VarbinRegProcessContentStdin;
            }
        }

        public string VarbinTestButtomText
        {
            set
            {
                VarbinTestButtomTextStdin = value;
                propertyChangeSend(nameof(VarbinTestButtomText));
            }
            get
            {
                return VarbinTestButtomTextStdin;
            }
        }

        public string VarbinRegProductHint
        {
            set
            {
                VarbinRegProductHintStdin = value;
                propertyChangeSend(nameof(VarbinRegProductHint));
            }
            get
            {
                return VarbinRegProductHintStdin;
            }
        }

        public string VarbinRegProcessHint
        {
            set
            {
                VarbinRegProcessHintStdin = value;
                propertyChangeSend(nameof(VarbinRegProcessHint));
            }
            get
            {
                return VarbinRegProcessHintStdin;
            }
        }

        public string VarbinRegChildKeyHint
        {
            set
            {
                VarbinRegChildKeyHintStdin = value;
                propertyChangeSend(nameof(VarbinRegChildKeyHint));
            }
            get
            {
                return VarbinRegChildKeyHintStdin;
            }
        }

        public string VarbinProductTreeExtendText
        {
            set
            {
                VarbinProductTreeExtendTextStdin = value;
                propertyChangeSend(nameof(VarbinProductTreeExtendText));
            }
            get
            {
                return VarbinProductTreeExtendTextStdin;
            }
        }

        private ObservableCollection<string> ProductSelectedValueStdin = [];

        private Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>> ProductSelectItemPairStdin = [];

        public ObservableCollection<object> DynamicRichContent { get; } = [];

        public ObservableCollection<string> ProductSelectedValue
        {
            set
            {
                ProductSelectedValueStdin = value;
                propertyChangeSend(nameof(ProductSelectedValue));
            }
            get
            {
                return ProductSelectedValueStdin;
            }
        }

        public ObservableCollection<string> ConfigurableSelectedValue { get; } = [];

        public ObservableCollection<string> LeisureProducts { get; } = []; //  单产品名称集合

        public ObservableCollection<KeyValuePairSealed> ConfigurableSelectItems { get; } = [];

        public Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>> ConfigurableSelectItemPair { get; } = [];

        public ObservableCollection<KeyValuePairSealed> ProductSelectItems { get; } = [];

        public Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>> ProductSelectItemPair
        {
            set
            {
                ProductSelectItemPairStdin = value;
                propertyChangeSend(nameof(ProductSelectItemPair));
            }
            get
            {
                return ProductSelectItemPairStdin;
            }
        }

        public ObservableCollection<TestItemSurfaceSealed> ActivityExpoListItems { set; get; } = [];

        public ObservableCollection<TestItemDeepSeatedSealed> ActivityConfigListItems { set; get; } = [];

        private ICollection<TestItemDeepSeatedSealed> ActivityBackEchoListItems { set; get; } = [];

        public ObservableCollection<SupplementConfig> SupplementConfigListItems { get; } = [];

        public ActivityViewModel(IPowerPlantServer PowerPlantServer,
                                 IDataBaseServer DataBaseServer,
                                 IDenCryptoGraphicServer DenCryptoGraphicServer,
                                 IDirFileServer DirFileServer,
                                 IActivityDetetorServer ActivityDetetorServer)
        {
            PowerServer = PowerPlantServer;
            DBServer = DataBaseServer;
            IOServer = DirFileServer;
            CryptServer = DenCryptoGraphicServer;
            ActivityServer = ActivityDetetorServer;
            HoldMesResportServer = new MesResportServer(IOServer, HoldMesargGroups);
            ActivityDetetor = new ActivityDetetor(ReturnReceipt);
            ReadyWork();

        }

        public async Task iii()
        {
            await Task.Delay(2000);

            _ = DBServer.CloudAnchorChannel<ProductConfigRelation>(
            () =>
            {
                Logger.Print(RuntimeLog.LogType.Debug, "product relation update success， update config code now");
            },
            async () =>
            {
                if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                {
                    Supabase.Interfaces.ISupabaseTable<ProductConfigRelation, Supabase.Realtime.RealtimeChannel>? UpdateRelation =
                    CloudDB.From<ProductConfigRelation>();

                    if (true)
                    {
                        UpdateRelation
                        .Set(x => x.PrdName, "集中式和易充")
                        .Where(x => x.PrdName == "集中式和易充");
                    }

                    if (true)
                    {
                        UpdateRelation
                        .Set(x => x.PrdProcess, "老化前整机测试22")
                        .Where(x => x.PrdProcess == "老化前整机测试");
                    }

                    await UpdateRelation.Update();

                    Logger.Print(RuntimeLog.LogType.Fatal, "start product relation update");
                }
            },
            () =>
            {
                Logger.Print(RuntimeLog.LogType.Fatal, "product relation update fail");

            }, "UPDATE");
        }

        public ActivitySectionModel HoldActivitySectionModel
        {
            set
            {
                ActivitySectionModelStdin = value;
                propertyChangeSend(nameof(HoldActivitySectionModel));
            }
            get
            {
                ActivitySectionModelStdin ??= new ActivitySectionModel();
                return ActivitySectionModelStdin;
            }
        }

        public MesargGroups HoldMesargGroups
        {
            set
            {
                MesargGroupsStdin = value;
                propertyChangeSend(nameof(HoldMesargGroups));
            }
            get
            {
                MesargGroupsStdin ??= new MesResportServer.MesargGroups();
                return MesargGroupsStdin;
            }
        }

        public Deserted HoldDesertedOptions
        {
            get
            {
                DesertedOptionsStdin ??= new Deserted();
                return DesertedOptionsStdin;
            }
        }

        public DateTimePush HoldDateTimePush
        {
            set
            {
                DateTimePushStdin = value;
                propertyChangeSend(nameof(HoldDateTimePush));
            }
            get
            {
                DateTimePushStdin ??= new DateTimePush();
                return DateTimePushStdin;
            }
        }

        public StalkerStepTemplate HoldStalkerStepTemplate
        {
            set
            {
                StalkerStepTemplateStdin = value;
                propertyChangeSend(nameof(HoldDateTimePush));
            }
            get
            {
                StalkerStepTemplateStdin ??= new StalkerStepTemplate();
                return StalkerStepTemplateStdin;
            }
        }

        public ObservableCollection<TopMenuOptions> HoldTopMenuOptions { get; } = [];

        public Argument HoldArgumentOptions
        {
            set
            {
                ArgumentOptionsStdin = value;
            }
            get
            {
                ArgumentOptionsStdin ??= new Argument();
                return ArgumentOptionsStdin;
            }
        }

        public ObservableCollection<EmbeddedTreeStructure> HoldEmbeddedTreeStructures { get; } = [];

        public ObservableCollection<EmbeddedTreeStructure> HoldTestStatisticialTrees { get; } = [];

        public ObservableCollection<TestStatiSticalTemplate> HoldTestStatisticialTotal { get; } = [];

        public EmbeddedTreeStructureSelect SelectionTree { set; get; } = new();


        public EmbeddedTreeStructureSelect SelectionTreeStdin = new();

        public Visibility VarbinPRegChildVisible
        {
            set
            {
                VarbinPRegChildVisibleStdin = value;
                propertyChangeSend(nameof(VarbinPRegChildVisible));
            }
            get
            {
                return VarbinPRegChildVisibleStdin;
            }
        }

        public bool VarbinVsstMesFace
        {
            set
            {
                VarbinVsstMesFaceStdin = value;
                propertyChangeSend(nameof(VarbinVsstMesFace));
            }
            get
            {
                return VarbinVsstMesFaceStdin;
            }
        }

        public bool VarbinVsstMesMap
        {
            set
            {
                VarbinVsstMesMapStdin = value;
                propertyChangeSend(nameof(VarbinVsstMesMap));
            }
            get
            {
                return VarbinVsstMesMapStdin;
            }
        }

        public bool VarbinVsstStalker
        {
            set
            {
                VarbinVsstStalkerStdin = value;
                propertyChangeSend(nameof(VarbinVsstStalker));
            }
            get
            {
                return VarbinVsstStalkerStdin;
            }
        }

        public string MesargPushUrl
        {
            set
            {
                MesargPushUrlStdin = value;
                propertyChangeSend(nameof(MesargPushUrl));
            }
            get
            {
                return MesargPushUrlStdin;
            }
        }

        public UIBind VarbinUIBind
        {
            set
            {
                VarbinUIBindStdin = value;
                propertyChangeSend(nameof(VarbinUIBind));
            }
            get
            {
                return VarbinUIBindStdin;
            }
        }

        public double VarbinMenuOpacity
        {
            set
            {
                VarbinMenuOpacityStdin = value;
                propertyChangeSend(nameof(VarbinMenuOpacity));
            }
            get
            {
                return VarbinMenuOpacityStdin;
            }
        }

        public int VarbinArgumentFaceSpan
        {
            set
            {
                VarbinArgumentFaceSpanStsin = value;
                propertyChangeSend(nameof(VarbinArgumentFaceSpan));
            }
            get
            {
                return VarbinArgumentFaceSpanStsin;
            }
        }

        public ICommand CmdDBMapFileOpen
        {
            set
            {
                CmdDBMapFileOpenStdin = value;
            }
            get
            {
                CmdDBMapFileOpenStdin ??= new EasyCommand(DBReserveFileAddEvent, bool () => { return true; });
                return CmdDBMapFileOpenStdin;
            }
        }

        public ICommand CmdDBMapinfoSave
        {
            set
            {
                CmdDBMapinfoSaveStdin = value;
            }
            get
            {
                CmdDBMapinfoSaveStdin ??= new EasyCommand(DBReserveFileSaveEvent, bool () => { return true; });
                return CmdDBMapinfoSaveStdin;
            }
        }

        public ICommand CmdDBMapuiExit
        {
            set
            {
                CmdDBMapuiExitStdin = value;
            }
            get
            {
                CmdDBMapuiExitStdin ??= new EasyCommand(DBReserveFileExitEvent, bool () => { return true; });
                return CmdDBMapuiExitStdin;
            }
        }

        public ICommand CmdRegbindProduct
        {
            set
            {
                CmdRegbindProductStdin = value;
            }
            get
            {
                CmdRegbindProductStdin ??= new EasyCommand(RegProductTextChange, bool () => { return true; });
                return CmdRegbindProductStdin;
            }
        }

        public ICommand CmdRegbindProcess
        {
            set
            {
                CmdRegbindProcessStdin = value;
            }
            get
            {
                CmdRegbindProcessStdin ??= new EasyCommand(RegProcessTextChange, bool () => { return true; });
                return CmdRegbindProcessStdin;
            }
        }

        public ICommand CmdRegAccept
        {
            set
            {
                CmdRegAcceptStdin = value;
            }
            get
            {
                CmdRegAcceptStdin ??= new EasyCommand(RegisterAcceptEvent, bool () => { return true; });
                return CmdRegAcceptStdin;
            }
        }

        public ICommand CmdRegexit
        {
            set
            {
                CmdRegexitStdin = value;
            }
            get
            {
                CmdRegexitStdin ??= new EasyCommand(RegisterCancelEvent, bool () => { return true; });
                return CmdRegexitStdin;
            }
        }

        public ICommand CmdRegchildSwitch
        {
            set
            {
                CmdRegchildSwitchStdin = value;
            }
            get
            {
                CmdRegchildSwitchStdin ??= new EasyCommand(RegisterChildKeyEvent, bool () => { return true; });
                return CmdRegchildSwitchStdin;
            }
        }

        public ICommand CmdProductViewDelete
        {
            set
            {
                CmdProductViewDeleteStdin = value;
            }
            get
            {
                CmdProductViewDeleteStdin ??= new EasyCommand(ProductViewDeleteEvent, bool () => { return true; });
                return CmdProductViewDeleteStdin;
            }
        }

        public ICommand CmdProductViewUpdate
        {
            set
            {
                CmdProductViewUpdateStdin = value;
            }
            get
            {
                CmdProductViewUpdateStdin ??= new EasyCommand(ProductViewUpdateEvent, bool () => { return true; });
                return CmdProductViewUpdateStdin;
            }
        }

        public ICommand CmdProductViewExit
        {
            set
            {
                CmdProductViewExitStdin = value;
            }
            get
            {
                CmdProductViewExitStdin ??= new EasyCommand(ProductViewExitEvent, bool () => { return true; });
                return CmdProductViewExitStdin;
            }
        }

        public ICommand CmdTestStart
        {
            set
            {
                CmdTestStartStdin = value;
            }
            get
            {
                CmdTestStartStdin ??= new EasyCommand(TestStartChange, bool () => { return true; });
                return CmdTestStartStdin;
            }
        }

        public ICommand CmdTopMenuMouseOver
        {
            set
            {
                CmdTopMenuMouseOverStdin = value;
            }
            get
            {
                CmdTopMenuMouseOverStdin ??= new EasyCommand(TopMenuMouseOverEvent, bool () => { return true; });
                return CmdTopMenuMouseOverStdin;
            }
        }

        public ICommand CmdConfigChoice
        {
            set
            {
                CmdConfigChoiceStdin = value;
            }
            get
            {
                CmdConfigChoiceStdin ??= new EasyCommand(ConfigurableChangeEvent, bool () => true);
                return CmdConfigChoiceStdin;
            }
        }

        public ICommand CmdProductChoice
        {
            set
            {
                CmdProductChoiceStdin = value;
            }
            get
            {
                CmdProductChoiceStdin ??= new EasyCommand(ProductChangeEvent, bool () => true);
                return CmdProductChoiceStdin;
            }
        }

        public ICommand CmdProductTree
        {
            set
            {
                CmdProductTreeStdin = value;
            }
            get
            {
                CmdProductTreeStdin ??= new EasyCommand(ProductTreeEvent, bool () => true);
                return CmdProductTreeStdin;
            }
        }

        public ICommand CmdProductTreeExtend
        {
            set
            {
                CmdProductTreeExtendStdin = value;
            }
            get
            {
                CmdProductTreeExtendStdin ??= new EasyCommand(ProductTreeExtend, bool () => true);
                return CmdProductTreeExtendStdin;
            }
        }

        public ICommand CmdClearSerialOut
        {
            set
            {
                CmdClearSerialOutStdin = value;
            }
            get
            {
                CmdClearSerialOutStdin ??= new EasyCommand(ClearSerialOutEvent, bool () => true);
                return CmdClearSerialOutStdin;
            }
        }

        public ICommand CmdMesDataBinding
        {
            set
            {
                CmdMesDataBindingStdin = value;
            }
            get
            {
                CmdMesDataBindingStdin ??= new EasyCommand(MesMapOpenEvent, bool () => true);
                return CmdMesDataBindingStdin;
            }
        }

        public ICommand CmdAssistConfigOpen
        {
            set
            {
                CmdAssistConfigOpenStdin = value;
            }
            get
            {
                CmdAssistConfigOpenStdin ??= new EasyCommand((_object) => {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        VarbinVsstMesFace = !VarbinVsstMesFace;
                    });
                }, bool () => true);
                return CmdAssistConfigOpenStdin;
            }
        }

        public ICommand CmdStalkerStepShow
        {
            set
            {
                CmdStalkerStepShowStdin = value;
            }
            get
            {
                CmdStalkerStepShowStdin ??= new EasyCommand(StalkerStepOpenEvent, bool () => true);
                return CmdStalkerStepShowStdin;
            }
        }

        public ICommand CmdStalkerStepAdd
        {
            set
            {
                CmdStalkerStepAddStdin = value;
            }
            get
            {
                CmdStalkerStepAddStdin ??= new EasyCommand((param) =>
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        HoldStalkerStepTemplate.Templates.Add(new StalkerStepTemplate.Template());
                    });
                }, bool () => true);
                return CmdStalkerStepAddStdin;
            }
        }

        public ICommand CmdStalkerStepBfAdd
        {
            set
            {
                CmdStalkerStepBfAddStdin = value;
            }
            get
            {
                CmdStalkerStepBfAddStdin ??= new EasyCommand(StalkerStepBfAddEvent, bool () => true);
                return CmdStalkerStepBfAddStdin;
            }
        }

        public ICommand CmdStalkerStepBfTake
        {
            set
            {
                CmdStalkerStepBfTakeStdin = value;
            }
            get
            {
                CmdStalkerStepBfTakeStdin ??= new EasyCommand(StalkerStepBfTakeEvent, bool () => true);
                return CmdStalkerStepBfTakeStdin;
            }
        }

        public ICommand CmdStalkerStepTake
        {
            set
            {
                CmdStalkerStepTakeStdin = value;
            }
            get
            {
                CmdStalkerStepTakeStdin ??= new EasyCommand(StalkerStepTakeEvent, bool () => true);
                return CmdStalkerStepTakeStdin;
            }
        }

        public ICommand CmdStalkerFlagChange
        {
            set
            {
                CmdStalkerFlagChangeStdin = value;
            }
            get
            {
                CmdStalkerFlagChangeStdin ??= new EasyCommand(StalkerFlagChangeEvent, bool () => true);
                return CmdStalkerFlagChangeStdin;
            }
        }

        public ICommand CmdTopMenuTestStatistical
        {
            set
            {
                CmdTopMenuTestStatisticalStdin = value;
            }
            get
            {
                CmdTopMenuTestStatisticalStdin ??= new EasyCommand(TestStatisticalEvent, bool () => { return true; });
                return CmdTopMenuTestStatisticalStdin;
            }
        }

        public ICommand CmdTopMenuTestStatisticalFilter
        {
            set
            {
                CmdTopMenuTestStatisticalFilterStdin = value;
            }
            get
            {
                CmdTopMenuTestStatisticalFilterStdin ??= new EasyCommand(StatiSticalDateFilterEvent, bool () => true);
                return CmdTopMenuTestStatisticalFilterStdin;
            }
        }

        public ICommand CmdTopMenuTestStatisticalClose
        {
            set
            {
                CmdTopMenuTestStatisticalCloseStdin = value;
            }
            get
            {
                CmdTopMenuTestStatisticalCloseStdin ??= new EasyCommand((obj) =>
                {
                    HoldTestStatisticialTrees.Clear();
                    HoldTestStatisticialTotal.Clear();
                }, bool () => true);
                return CmdTopMenuTestStatisticalCloseStdin;
            }
        }

        public ICommand CmdRegexpTestTool
        {
            set
            {
                CmdTopMenuRegexpTestToolStdin = value;
            }
            get
            {
                CmdTopMenuRegexpTestToolStdin ??= new EasyCommand(RegexpTestToolEvent, bool () => true);
                return CmdTopMenuRegexpTestToolStdin;
            }
        }

        public ICommand CmdBitwiseXorTool
        {
            set
            {
                CmdTopMenuBitwiseXorToolStdin = value;
            }
            get
            {
                CmdTopMenuBitwiseXorToolStdin ??= new EasyCommand(BitwiseToolEvent, bool () => true);
                return CmdTopMenuBitwiseXorToolStdin;
            }
        }

        public ICommand CmdCaptrueDeepSeated
        {
            set
            {
                CmdCaptrueDeepSeatedStdin = value;
            }
            get
            {
                CmdCaptrueDeepSeatedStdin ??= new EasyCommand(CaptrueAttribute, bool () => true);
                return CmdCaptrueDeepSeatedStdin;
            }
        }

        public ICommand CmdCaptrueDBMapConfig
        {
            set
            {
                CmdCaptrueDBMapConfigStdin = value;
            }
            get
            {
                CmdCaptrueDBMapConfigStdin ??= new EasyCommand(CaptrueDBrelation, bool () => true);
                return CmdCaptrueDBMapConfigStdin;
            }
        }

        public ICommand CmdCaptrueMesMapConfig
        {
            set
            {
                CmdCaptrueMesMapConfigStdin = value;
            }
            get
            {
                CmdCaptrueMesMapConfigStdin ??= new EasyCommand(CaptrueMesrelation, bool () => true);
                return CmdCaptrueMesMapConfigStdin;
            }
        }

        public ICommand CmdMesinfoMapExit
        {
            set
            {
                CmdMesinfoMapExitStdin = value;
            }
            get
            {
                CmdMesinfoMapExitStdin ??= new EasyCommand(CaptrueMesrelation, bool () => true);
                return CmdMesinfoMapExitStdin;
            }
        }

        public ICommand CmdHyperlinkReceive
        {
            set
            {
                CmdHyperlinkReceiveStdin = value;
            }
            get
            {
                CmdHyperlinkReceiveStdin ??= new EasyCommand(HyperLinkFactory, bool () => true);
                return CmdHyperlinkReceiveStdin;
            }
        }

        private void UIload(Interfacial _UIType)
        {
            VarbinUIBind.UIType = _UIType;
            propertyChangeSend(nameof(VarbinUIBind));
        }

        //  开始测试
        private async void TestStartChange(object? param)
        {
            try
            {
                await RecoverEctivityListItem();

                if (ActivityDetetor.State())
                {
                    ActivityDetetor.Start(false);
                }
                
                else
                {
                    if (PowerServer.Action(2).Item1)
                    {
                        await ActivityDetetor.SetMainAccording(
                            HoldArgumentOptions.Imei,
                            HoldArgumentOptions.Sn,
                            HoldArgumentOptions.Blue,
                            HoldArgumentOptions.Doid,
                            HoldArgumentOptions.Qrcode1,
                            HoldArgumentOptions.Qrcode2);

                        if (SupplementConfigListItems.Count > 0)
                        {
                            if (SupplementConfigListItems.Where(x => !string.IsNullOrEmpty(x.Value)).Count() == SupplementConfigListItems.Count)
                            {
                                ActivityDetetor.SetAtrributeAlter(SupplementConfigListItems);
                            }
                            else
                            {
                                await CustomMessageBox.Show(new CustomMessageBox.InquiryNmPopupSetting
                                {
                                    Msg_Title = "数据为空",
                                    Msg_InquiryIcon = 1,
                                    Msg_InquiryButtoms = ["知道了"],
                                    Msg_BodyText = $"补充数据{SupplementConfigListItems.Select(x => x.Name).Join("、")}不能为空",
                                    Msg_WinWidth = 350,
                                    Msg_WinHeight = 180
                                });
                                return;
                            }
                        }

                        //  <!-- 重置日志记录器，避免无效数据污染 -->
                        HoldActivitySectionModel.Device_TestRunningRecor.Clear();
                        HoldActivitySectionModel.Tools_TestRunningRecor.Clear();
                        HoldActivitySectionModel.Device_TestRunningRecor.Capacity = 4096;
                        HoldActivitySectionModel.Tools_TestRunningRecor.Capacity = 4096;

                        List<TestItemDeepSeatedSealed> ApplyItems = [.. ActivityConfigListItems.Where(x => x.Status)];

                        ActivityDetetor.Actvt_PapPair = HoldActivitySectionModel.ProductSelectedValuePair; //  设置产测 产品 和 工序

                        //  未执行的原因，没有判断主key不存在的情况，ReadMesAbnormalinLoacal 方法缺陷
                        if (HoldActivitySectionModel.TestDemandType == DemandType.Mes)
                        {
                            if (HoldActivitySectionModel.MesConfigMap.TryGetValue(ActivityDetetor.Actvt_PapPair.Item2, out KvpGroup _struct))
                            {
                                if (await HoldActivitySectionModel.AsyncLock.WaitAsync(TimeSpan.FromMilliseconds(200)))
                                {
                                    string bingdingContent = _struct.SHowyDatas.ElementAt(3).Content;

                                    string bindingValue = string.Empty;

                                    if (bingdingContent == "IMEI")
                                    {
                                        bindingValue = HoldArgumentOptions.Imei;
                                    }
                                    else if (bingdingContent == "QRCODE" || (bingdingContent.Contains("IMEI") && bingdingContent.Contains("QRCODE")))
                                    {
                                        bindingValue = HoldMesargGroups.Barcodes;
                                    }

                                    //  无论有没有异常缓存，都会触发回调。以url是否为空为补发依据，因为一旦url为空，后续的补发操作将无意义
                                    await HoldMesResportServer.ReadMesAbnormalinLoacal(async (MesRequest, _apiUrl) =>
                                    {
                                        ActivityDetetor.Start(true);
                                        try
                                        {
                                            Logger.Print(RuntimeLog.LogType.Debug, "read loacal mes info : ", _apiUrl, string.IsNullOrEmpty(_apiUrl));

                                            //  不存在异常报告数据时，正常执行测试流程
                                            if (string.IsNullOrEmpty(_apiUrl))
                                            {
                                                await HoldMesResportServer.SaveMesinLoacal(MesResportServer.GetPrimaryKey(ExpectedPrimaryKey.MesBaseCache), MesargPushUrl);

                                                await ActivityDetetor.ReadyRunning(ApplyItems);

                                                Logger.Print(RuntimeLog.LogType.Debug, "save report cache and begin running now");
                                            }
                                            else
                                            {
                                                Action ResendAction = await CustomMessageBox.Show(new CustomMessageBox.InquiryDlPopupSetting
                                                {
                                                    Msg_Title = "MES补发",
                                                    Msg_BodyText = "正在补发MES上报...",
                                                    Msg_Result = 1,
                                                    Msg_WinRadius = 6,
                                                    Msg_CloseCallback = null,
                                                    Msg_DelayExitTime = null
                                                });

                                                await HttpResend();

                                                async Task HttpResend()
                                                {
                                                    Response? HttpResponse = await HoldMesResportServer.HttpRequest(MesRequest, _apiUrl, false);

                                                    if (HttpResponse is not null && HttpResponse.status == 0)
                                                    {
                                                        ResendAction.Invoke();
                                                        CustomMessageBox.InquiryPopupInvoke invoke = await CustomMessageBox.Show(
                                                            new CustomMessageBox.InquiryNmPopupSetting
                                                            {
                                                                Msg_Title = "MES报告发送失败",
                                                                Msg_BodyText = "1. [开始编辑] -> 打开缓存文件,选择 [mes_abnormal_cache]信息栏，编辑正确信息后点击 [开始测试] 进行重发\n\n" +
                                                                               "2. [重试发送] -> 如网络问题，点击该按钮重发\n\n" +
                                                                               $"详情:\n\r {HttpResponse.returninfo}",
                                                                Msg_HAlignment = System.Windows.HorizontalAlignment.Left,
                                                                Msg_WinWidth = 388,
                                                                Msg_WinHeight = 256
                                                            });

                                                        if (invoke.index == 0)
                                                        {
                                                            try
                                                            {
                                                                IOServer.OpenFile(LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.Mes));
                                                            }
                                                            catch (Exception error)
                                                            {
                                                                Logger.Print(RuntimeLog.LogType.Error, $"abnormal cache file open Error: {error.Message}");
                                                            }
                                                        }
                                                        else if (invoke.index == 1)
                                                        {
                                                            await HttpResend();
                                                        }
                                                        ActivityDetetor.Start(false); //  手动更新测试状态
                                                    }
                                                    else
                                                    {
                                                        ResendAction.Invoke();
                                                        await CustomMessageBox.Show(
                                                            new CustomMessageBox.InquiryDlPopupSetting
                                                            {
                                                                Msg_Title = "MES报告补发",
                                                                Msg_BodyText = "MES报告补发成功",
                                                                Msg_DelayExitTime = 3500,
                                                                Msg_Result = 2
                                                            });

                                                        ActivityDetetor.Start(true);
                                                        await HoldMesResportServer.SaveMesinLoacal(MesResportServer.GetPrimaryKey(ExpectedPrimaryKey.MesBaseCache), MesargPushUrl);
                                                        await ActivityDetetor.ReadyRunning(ApplyItems);
                                                        await IOServer.WriteIniAsync(LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.Mes),
                                                                                          bindingValue, null);
                                                    }
                                                }
                                            }
                                        }
                                        finally
                                        {
                                            if (HoldActivitySectionModel.AsyncLock.CurrentCount == 0)
                                            {
                                                HoldActivitySectionModel.AsyncLock.Release();
                                                HoldActivitySectionModel.SemaphoreAbnormalStat = false;
                                                Logger.Print(RuntimeLog.LogType.Fatal, "Mes send finish, release _AsyncLock now");
                                            }
                                        }
                                    }, bindingValue);
                                }
                                else
                                {
                                    if (!HoldActivitySectionModel.SemaphoreAbnormalStat)
                                    {

                                        HoldActivitySectionModel.SemaphoreAbnormalStat = true;
                                        await Task.Delay(6000);
                                        if (HoldActivitySectionModel.AsyncLock.CurrentCount == 0)
                                        {
                                            HoldActivitySectionModel.AsyncLock.Release();
                                            HoldActivitySectionModel.SemaphoreAbnormalStat = false;
                                        }
                                        Logger.Print(RuntimeLog.LogType.Fatal, "_AsyncLock await fail, release now");
                                    }
                                }
                            } // ************************** 因为没有使用else，导致执行了两个ReadyRunning 流程，步骤错乱混淆
                            else
                            {
                                ActivityDetetor.Start(true);
                                await ActivityDetetor.ReadyRunning(ApplyItems);
                            }
                        }
                        
                        else
                        {
                            ActivityDetetor.Start(true);
                            await ActivityDetetor.ReadyRunning(ApplyItems);

                        }
                    }
                    else ReturnReceipt(new FlyingDove(MessageProPlantType.Message, "串口未打开"));
                }
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  重置测试项状态
        private async Task RecoverEctivityListItem()
        {
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                for (int index = 0; index < ActivityExpoListItems.Count; index++)
                {
                    ActivityExpoListItems[index] = new TestItemSurfaceSealed(ActivityExpoListItems[index].ActivityName, "MustardPop".FindSolidBrush());
                }
                propertyChangeSend(nameof(ActivityExpoListItems));
            });
        }

        //  添加数据库映射参考文件
        private async void DBReserveFileAddEvent(object? param)
        {
            try
            {
                OpenFileDialog FileSelector = new()
                {
                    DefaultDirectory = "dir".CurrentDir(),
                    Filter = "Excel Files (*.xlsx, *.xls, *.csv)|*.xlsx;*.xls;*.csv|All Files (*.*)|*.*",
                    Multiselect = false
                };

                if (FileSelector.ShowDialog() is not null and bool)
                {
                    ICollection<string> consultColumns = await GetConsultWorkOrderField(FileSelector.FileName);
                    GetDBfieldMapInfos(consultColumns);
                }
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  添加数据库映射参考列
        private async Task<ICollection<string>> GetConsultWorkOrderField(string CstWorkOrderFile)
        {
            ICollection<string> CusultColumnNames = [];
            try
            {
                Excel excel = new(HoldActivitySectionModel.DBWorkOrderMap, DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Cloud);

                Action<double, string?>? Progress = null;

                Dictionary<string, Dictionary<string, ICollection<string>>> ReadContentMap = await excel.AutoRead(new ExcelOptions([CstWorkOrderFile])
                {
                    Exc_HintCallBack = async (sheet, hint, process) =>
                    {
                        Progress ??= await CustomMessageBox.Show(new CustomMessageBox.ShowyPrograssSetting());
                        Progress?.Invoke(process, $"工作簿: {sheet} {hint} 读取中...");
                    },
                    Exc_MaxReaderNum = 2,
                    Exc_VisiblePrograss = false
                });

                await Task.Run(() =>
                {
                    foreach (var kvp in ReadContentMap)
                    {
                        if (kvp.Value.TryGetValue("Title", out ICollection<string>? Titles))
                        {
                            CusultColumnNames = Titles;
                            break;
                        }
                    }
                });
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
            return CusultColumnNames;
        }

        //  字段映射保存
        private void DBReserveFileSaveEvent(object? param)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                HoldDesertedOptions.CapCTDBfieldConfig = true;
            });
        }

        //  退出字段映射
        private void DBReserveFileExitEvent(object? param)
        {
            UIload(Interfacial.PRDTProductOutTextBox);
        }

        //  注册子键 / 主键切换
        private void RegisterChildKeyEvent(object? param)
        {
            try
            {
                if (param is not null)
                {
                    HoldActivitySectionModel.RegisterIsSecondaryKey = int.Parse(param.GetSafetyChar());
                    switch (HoldActivitySectionModel.RegisterIsSecondaryKey)
                    {
                        case 1:
                            VarbinPRegChildVisible = Visibility.Visible;
                            VarbinRegProductHintStdin = "关联主键";
                            VarbinRegProcessHint = "子键名称";
                            VarbinRegChildKeyHint = "是子键";
                            break;

                        case 0:
                            VarbinPRegChildVisible = Visibility.Collapsed;
                            VarbinRegProductHintStdin = "主键名称";
                            VarbinRegChildKeyHint = "是否子键";
                            VarbinRegProcessContent = string.Empty;
                            break;
                    }
                }
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  获取注册产品名称
        private void RegProductTextChange(object? param)
        {
            if (param is not null)
            {
                VarbinRegProductContent = param.GetSafetyChar();
            }
        }

        //  获取注册产工序
        private void RegProcessTextChange(object? param)
        {
            if (param is not null)
            {
                VarbinRegProcessContent = param.GetSafetyChar();
            }
        }

        //  配置选项选择
        private void ConfigurableChangeEvent(object? param)
        {
            try
            {
                //  确保数据发送到UI线程，但是不能使用异步，否则会造成数据丢失(可能异步机制与MVVM冲突)
                Application.Current.Dispatcher.Invoke(async () =>
                {
                    if (param is not null and List<string> selects && selects.Count >= 1)
                    {
                        string key = selects[0];

                        switch (key)
                        {
                            case "添加步骤":
                                if (VarbinUIBind.UIType == Interfacial.PRDTAttributeConfig)
                                {
                                    if (selects.Count >= 2)
                                    {
                                        HoldDesertedOptions.IFLoadAttrStepAddPush = selects[1];
                                    }
                                }
                                break;

                            case "编辑配置":

                                if (VarbinUIBind.UIType != Interfacial.PRDTAttributeConfig)
                                {
                                    if (!string.IsNullOrEmpty(HoldActivitySectionModel.ProductSelectedValuePair.Item1))
                                    {
                                        ActivityAssistBehivor.Behivor.AttributeConfigProductType = HoldActivitySectionModel.ProductSelectedValuePair.Item1;
                                    }
                                    VarbinUIBind.InstantiationCallBack = () =>
                                    {
                                        HoldDesertedOptions.IFLoadAttrItemsAddPush = [..ActivityConfigListItems];
                                    };
                                    UIload(Interfacial.PRDTAttributeConfig);
                                }
                                break;

                            case "保存配置":
                                if (VarbinUIBind.UIType == Interfacial.PRDTAttributeConfig)
                                {
                                    HoldDesertedOptions.CapCTAttributeConfig = true;
                                }
                                break;

                            case "退出配置":
                                if (VarbinUIBind.UIType == Interfacial.PRDTAttributeConfig)
                                {
                                    UIload(Interfacial.PRDTProductOutTextBox);
                                }
                                break;

                            case "回滚配置":
                                CaptrueAttribute(ActivityBackEchoListItems);
                                break;

                            case "导入配置":
                                if (selects.Count > 1 && VarbinUIBind.UIType == Interfacial.PRDTAttributeConfig)
                                {
                                    await IOServer.GetLocalFilesAsync(new LocalFileFilterOptions
                                    (
                                        Directory.GetCurrentDirectory(),
                                        selects.ElementAt(1),
                                        "ini",
                                        async (file) =>
                                        {
                                            string? content = await IOServer.ReadAsync(file.Item1);

                                            if (content is not null)
                                            {
                                                List<TestItemDeepSeatedSealed>? DeepConfigs = JsonSerializer.Deserialize<List<TestItemDeepSeatedSealed>>(
                                                    content,
                                                    Function.SafetyReferenceJsonOptions);
                                                HoldDesertedOptions.IFLoadAttrItemsAddPush = DeepConfigs;
                                                file.Item2.Cancel();
                                            }
                                        },
                                        LocalFileFilterOptions.Mode.Exact
                                    ));
                                }
                                break;

                            case "导出配置":
                                _ = ActivityServer.ConfigTemplateCreator(Function.SafetyReferenceJsonOptions);
                                break;
                        }
                    }
                });
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  清空输出内容
        private void ClearSerialOutEvent(object? param)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                HoldDesertedOptions.DoCtClearRichBox = true;
            });
        }

        //  更新应用产品标识
        private async void UpdateProductApplyFlag(string product, string process)
        {
            DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));
            
            if (DBTYPE == DB.DB_TYPE.DB_Cloud)
            {
                if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                {
                    await CloudDB.From<ProductConfigRelation>()
                                    .Where(x => x.PrdId != null && x.PrdId != "")
                                    .Set(x => x.PrdApply, 0).Update();

                    await CloudDB.From<ProductConfigRelation>()
                                    .Where(x => x.PrdName == product && x.PrdProcess == process)
                                    .Set(x => x.PrdApply, 1).Update();
                }
            }
                
            else if (DBTYPE == DB.DB_TYPE.DB_Local)
            {
                await DBServer.LocalDBQueryFree($"UPDATE product_config_relation SET prd_apply={0}",
                                                $"UPDATE product_config_relation SET prd_apply={1} WHERE " +
                                                $"prd_name='{product}' and prd_process='{process}'");
                    
            }
        }

        //  产品工序选择
        private void ProductChangeEvent(object? param)
        {
            try
            {
                Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    if (param is not null and List<string> selector)
                    {
                        bool isTreeChild = selector.Count >= 2 && !string.IsNullOrEmpty(selector[0]) && !string.IsNullOrEmpty(selector[1]);
                        string key = selector[0];

                        if (key == "产品管理")
                        {
                            string function = selector[1];
                            switch (function)
                            {
                                case "产品添加":
                                    UIload(Interfacial.PRDTProductRegister);
                                    break;

                                case "产品预览":
                                    ReworkProductTreeData(() =>
                                    {
                                        UIload(Interfacial.PRDTProductPreView);
                                    });
                                    break;
                            }
                        }

                        else if (key == "预置数据库" && isTreeChild)
                        {
                            string function = selector[1];

                            switch (function)
                            {
                                case "工单添加":
                                    WorkOrderImport();
                                    break;

                                case "工单预览":
                                    ActivityServer.WorkorderPreviewUIShow(() =>
                                    {
                                        VarbinVsstMesMap = false;
                                    },
                                    //  清楚本地MES痕迹
                                    async (imeis) =>
                                    {
                                        Dictionary<string, Dictionary<string, string>> MesMap = await IOServer.ReadIniAsync(
                                                LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.Mes));

                                        List<string> Relations = [];

                                        foreach (var kvp in MesMap)
                                        {
                                            foreach (var imei in imeis)
                                            {
                                                if (ActivityAssistBehivor.Behivor.MesTranslationMap.TryGetValue(nameof(MesargGroups.Barcodes), out (string, bool) _TransBarcodes) && 
                                                    kvp.Value.TryGetValue(_TransBarcodes.Item1, out string? _Barcodes))
                                                {
                                                    Relations.Add(_Barcodes);

                                                    if (ActivityAssistBehivor.Behivor.MesTranslationMap.TryGetValue(nameof(MesargGroups.BindingInfo), out (string, bool) _TransBindingInfos) &&
                                                        kvp.Value.TryGetValue(_TransBindingInfos.Item1, out string? _BindingInfo) && _BindingInfo.Contains(imei))
                                                    {
                                                        Relations.Add(imei);
                                                        Relations.Add(kvp.Key);
                                                    }
                                                }
                                            }
                                        }

                                        foreach (var data in Relations)
                                        {
                                            int index = 0;
                                            int maxTry = 3;

                                            while (index < maxTry)
                                            {
                                                await IOServer.WriteIniAsync(LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.Mes),
                                                                                  data, null);
                                                if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Cloud)
                                                {
                                                    if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                                                    {
                                                        await CloudDB.From<TestResultRegister>()
                                                        .Where(x => x.Imei == data)
                                                        .Delete();
                                                    }
                                                }
                                                else if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Local)
                                                {
                                                    string DeleteStatisticalSql = $"DELETE FROM testresult_register WHERE imei='{data}'";
                                                    await DBServer.LocalDBQueryFree(DeleteStatisticalSql);
                                                }

                                                if (!(await IOServer.ReadIniAsync(
                                                      LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.Mes))).ContainsKey(data))
                                                {
                                                    break;
                                                }
                                                index++;
                                            }
                                        }
                                    });
                                    break;

                                case "字段映射":
                                    UIload(Interfacial.PRDTDBmapUI);
                                    VarbinUIBind.InstantiationCallBack = () =>
                                    {
                                        KeyValuePair<Dictionary<string, string>, ICollection<string>> infoGrounp = new(
                                                            HoldActivitySectionModel.DBWorkOrderMap,
                                                            HoldActivitySectionModel.CusultColumnNames);

                                        HoldDesertedOptions.IFLoadDBMapInfoPush = infoGrounp;

                                        propertyChangeSend(nameof(HoldDesertedOptions));
                                    };
                                    break;
                            }
                        }

                        else
                        {
                            if (isTreeChild)
                            {
                                string product = selector[0];
                                string process = selector[1];
                                VarbinRegProductContent = product;

                                if (HoldActivitySectionModel.ProductSelectedValuePair.Item1 != product ||
                                    HoldActivitySectionModel.ProductSelectedValuePair.Item2 != process)
                                {
                                    if (!ActivityAssistBehivor.Behivor.ProductFixedOpptions.Any(x => x.Key.Name.Contains(product)))
                                    {
                                        HoldActivitySectionModel.ProductSelectedValuePair = (product, process);
                                        GetDBfieldMapInfos();
                                    }

                                    UpdateProductApplyFlag(product, process);

                                    GetConfigInfos(selector[0], selector[1]);

                                    _ = TestStatisticalLoader(HoldActivitySectionModel.ProductSelectedValuePair.Item1, HoldDateTimePush, true);
                                }

                                ProductSubjoinAssert(key);
                            }
                        }
                    }
                }, DispatcherPriority.Background);
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  打开自定义悬浮岛
        private void TopMenuMouseOverEvent(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                if (param is not null and bool _IsMoueseOver)
                {
                    if (_IsMoueseOver)
                    {
                        VarbinMenuOpacity = 0.1; //  设置0.1透明度，以触发IsMouseOver 属性值更新
                    }
                }
            });
        }

        //  打开正则调试工具
        private void RegexpTestToolEvent(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                ActivityServer.RegexpTestToolUIShow(new RegexpTestTool.InfoPakage());
            });
        }

        //  打开位异或查看工具
        private void BitwiseToolEvent(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                ActivityServer.BitwiseXorToolUIShow(string.Empty);
            });
        }

        //  测试结果统计数据,打开
        private void TestStatisticalEvent(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                ActivityServer.TestStatisticalViewUIShow();
             });
        }

        //  测试结果统计数据,加载
        private async Task TestStatisticalLoader(string product, DateTimePush DateOptions, bool updateDate = true)
        {
            if (HoldDateTimePush.CanUpdateData(HoldActivitySectionModel.ProductSelectedValuePair.Item1))
            {
                await Application.Current.Dispatcher.InvokeAsync(async () =>
                {
                    DateOptions.Query = "查询中...";

                    HoldTestStatisticialTrees.Clear();
                    HoldTestStatisticialTotal.Clear();

                    if (updateDate)
                    {
                        HoldDateTimePush.Starts.Clear();
                        HoldDateTimePush.Ends.Clear();
                    }

                    DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));

                    async Task Prepare(IEnumerable<TestResultRegister> Datas)
                    {
                        IEnumerable<string> TotalPassDatas = Datas.Where(x => x.Result).DistinctBy(x => x.Imei).Select(x => x.Imei);

                        EmbeddedTreeStructure TotalCountHint = new()
                        {
                            TreeName = $"{HoldActivitySectionModel.ProductSelectedValuePair.Item1}测试总计：{Datas.DistinctBy(x => x.Imei).Count()}", //  All
                            TreeIcon = EmbeddedTreeStructure.Icon(),
                            ExtraBindDing = EmbeddedTreeStructure.Identity.Nonaligned,
                            IsChild = false,
                            IsExpand = false
                        };

                        EmbeddedTreeStructure TotalPassTree = new()
                        {
                            TreeName = "测试通过",
                            TreeCount = TotalPassDatas.Count(),
                            TreeIcon = EmbeddedTreeStructure.Icon(),
                            ExtraBindDing = EmbeddedTreeStructure.Identity.Friendly,
                            IsChild = false,
                            IsExpand = false,
                        };

                        EmbeddedTreeStructure TotalFailTree = new()
                        {
                            TreeName = "测试不通过",
                            TreeCount = Datas.Where(x => !x.Result).DistinctBy(x => x.Imei).Select(x => x.Imei).Where(x => !TotalPassDatas.Contains(x)).Count(),
                            TreeIcon = EmbeddedTreeStructure.Icon(),
                            ExtraBindDing = EmbeddedTreeStructure.Identity.Unamiable,
                            IsChild = false,
                            IsExpand = false,
                        };

                        HoldTestStatisticialTrees.AddRange([TotalCountHint, TotalPassTree, TotalFailTree]);

                        foreach (var data in Datas)
                        {
                            //  统计信息
                            if (await FindTemplate(HoldTestStatisticialTotal, data.Process, data.Step) is not null and //  ********问题代码。找不到Step
                                List<TestStatiSticalTemplate.InnerDatas> _InnerTemplates &&
                                _InnerTemplates.Count != 0)
                            {
                                await LoopStep(data.Step, data.Result, _InnerTemplates);
                            }
                            else
                            {
                                if (!HoldTestStatisticialTotal.Where(x => x.TestProcess == data.Process).Any())
                                {
                                    ObservableCollection<TestStatiSticalTemplate.InnerDatas> LoopDatas = await LoopStep(data.Step, data.Result);

                                    TestStatiSticalTemplate _NewTemplate = new()
                                    {
                                        TestProcess = data.Process,
                                        InnerSources = LoopDatas
                                    };

                                    HoldTestStatisticialTotal.Add(_NewTemplate);
                                }
                            }
                            //  树状图信息
                            await LoaderForSingleData(data.Result, data.Process, data.Imei, data.Step, data.Origin, data.Date);
                        }
                    }

                    async Task<ObservableCollection<TestStatiSticalTemplate.InnerDatas>> LoopStep(string step, bool result,
                          List<TestStatiSticalTemplate.InnerDatas>? ConsultDatas = null)
                    {
                        ObservableCollection<TestStatiSticalTemplate.InnerDatas> InnerSources = [];

                        await Task.Run(() =>
                        {
                            void CountAdd(bool result, string fullstep, string realstep, TestStatiSticalTemplate.InnerDatas source)
                            {
                                if (result)
                                {
                                    source.TestPassCount++;
                                }
                                else
                                {
                                    if (fullstep.Contains("不通过"))
                                    {
                                        source.TestFailCount++;
                                    }
                                    else
                                    {
                                        source.TestPassCount++;
                                    }
                                }
                            }

                            string[] Steps = RegExp.RegExpAndSpacing().Split(step);
                            foreach (var _fullStep in Steps)
                            {
                                string[] SplitStep = _fullStep.Split(':');
                                string RealStep = SplitStep.Length == 2 ? SplitStep.ElementAt(0) : _fullStep;

                                if (ConsultDatas is null)
                                {
                                    var FindExists = InnerSources.Where(x => x.TestStep.Equals(RealStep, StringComparison.InvariantCultureIgnoreCase));
                                    if (!FindExists.Any())
                                    {
                                        TestStatiSticalTemplate.InnerDatas NewInner = new() { TestStep = RealStep };
                                        CountAdd(result, _fullStep, RealStep, NewInner);
                                        if (NewInner is not null) InnerSources.Add(NewInner);
                                    }
                                }
                                else
                                {
                                    var FindExists = ConsultDatas.Where(x => x.TestStep.Equals(RealStep, StringComparison.InvariantCultureIgnoreCase));

                                    if (FindExists.Any())
                                    {
                                        TestStatiSticalTemplate.InnerDatas FindExist = FindExists.ElementAt(0);
                                        CountAdd(result, _fullStep, RealStep, FindExist);
                                    }
                                    else
                                    {
                                        TestStatiSticalTemplate.InnerDatas NewInner = new() { TestStep = RealStep };
                                        CountAdd(result, _fullStep, RealStep, NewInner);
                                        ConsultDatas.Add(NewInner);
                                    }
                                }
                            }
                        });

                        return InnerSources;
                    }

                    async Task<EmbeddedTreeStructure?> FindTree(IEnumerable<EmbeddedTreeStructure>? Sources, string key)
                    {
                        EmbeddedTreeStructure? Tree = null;

                        await Task.Run(() =>
                        {

                            if (Sources is not null)
                            {
                                IEnumerable<EmbeddedTreeStructure> Trees = Sources.Where(x => x.TreeName == key);
                                if (Trees.Any()) Tree = Trees.ElementAt(0);
                            }
                        });

                        return Tree;
                    }

                    async Task<List<TestStatiSticalTemplate.InnerDatas>> FindTemplate(IEnumerable<TestStatiSticalTemplate> Sources, string process, string step)
                    {
                        List<TestStatiSticalTemplate.InnerDatas> Inners = [];

                        await Application.Current.Dispatcher.InvokeAsync(() =>
                        {

                            TestStatiSticalTemplate? Template = Sources.FirstOrDefault(x => x.TestProcess == process);

                            if (Template != null)
                            {
                                foreach (var combination in RegExp.RegExpAndSpacing().Split(step))
                                {
                                    string[] splitStep = combination.Split(':');
                                    if (splitStep.Length == 2)
                                    {
                                        string step = combination.Split(':').ElementAt(0);
                                        TestStatiSticalTemplate.InnerDatas? FindInner = Template.InnerSources.FirstOrDefault(x => x.TestStep == step);

                                        if (FindInner is null)
                                        {
                                            TestStatiSticalTemplate.InnerDatas NewInner = new() { TestStep = step };
                                            Template.InnerSources.Add(NewInner);
                                            Inners.Add(NewInner);
                                        }
                                        else
                                        {
                                            Inners.Add(FindInner);
                                        }
                                    }
                                }
                            }
                        });
                        return Inners;
                    }

                    async Task LoaderForSingleData(bool _result, string _process, string _imei, string _step, string _origin, string _date)
                    {
                        try
                        {
                            await Task.Run(async () =>
                            {
                                string chz_result = _result ? "测试通过" : "测试不通过";
                                EmbeddedTreeStructure? FindMain = await FindTree(HoldTestStatisticialTrees, chz_result);
                                if (FindMain is not null)
                                {
                                    EmbeddedTreeStructure? FindProcess = await FindTree(FindMain.ProductRelationChildTree, _process);
                                    if (FindProcess is null && !string.IsNullOrEmpty(_process.Trim()))
                                    {
                                        EmbeddedTreeStructure ProcessTree = new()
                                        {
                                            TreeIcon = EmbeddedTreeStructure.Icon(false),
                                            TreeName = _process,
                                            IsChild = true,
                                            TreeCount = 0,
                                            IsExpand = false,
                                            TreeParent = chz_result,
                                            ExtraBindDing = EmbeddedTreeStructure.Identity.Nonaligned
                                        };

                                        FindMain.ProductRelationChildTree.Add(ProcessTree);
                                        FindProcess = ProcessTree;
                                    }


                                    EmbeddedTreeStructure? FindImei = await FindTree(FindProcess?.ProductRelationChildTree, _imei);

                                    if (FindImei is null && !string.IsNullOrEmpty(_imei.Trim()) ||
                                       (FindImei is not null && FindImei.Date != _date))
                                    {
                                        EmbeddedTreeStructure ImeiTree = new()
                                        {
                                            TreeIcon = EmbeddedTreeStructure.Icon(false),
                                            TreeName = _imei,
                                            Date = _date,
                                            IsChild = true,
                                            IsExpand = false,
                                            TreeParent = FindProcess is null ? string.Empty : FindProcess.TreeName,
                                            ExtraBindDing = EmbeddedTreeStructure.Identity.Nonaligned
                                        };

                                        if (FindProcess is not null)
                                        {
                                            FindProcess.ProductRelationChildTree.Add(ImeiTree);
                                            FindProcess.TreeCount++;
                                            FindImei = ImeiTree;
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(_step.Trim()))
                                    {
                                        IEnumerable<string> ColleSteps = RegExp.RegExpAndSpacing().Split(_step)
                                                        .Where(x => !string.IsNullOrEmpty(x));

                                        if (FindImei is not null)
                                        {
                                            foreach (var _dtstep in ColleSteps)
                                            {
                                                if (!FindImei.ProductRelationChildTree.Select(x => x.TreeName).Contains(_dtstep))
                                                {
                                                    EmbeddedTreeStructure EmbeddedStep = new()
                                                    {
                                                        TreeIcon = EmbeddedTreeStructure.Icon(false),
                                                        TreeName = _dtstep,
                                                        IsChild = true,
                                                        IsExpand = false,
                                                        TreeParent = FindImei.TreeName,
                                                        ExtraBindDing = EmbeddedTreeStructure.Identity.Nonaligned
                                                    };

                                                    FindImei.ProductRelationChildTree.Add(EmbeddedStep);
                                                    FindImei.TreeCount++;
                                                }
                                            }
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(_origin.Trim()))
                                    {
                                        if (FindImei is not null && FindImei.ProductRelationChildTree.Count > 0)
                                        {
                                            if (!FindImei.ProductRelationChildTree.Last().ProductRelationChildTree.Select(x => x.TreeName).Contains(_origin))
                                            {
                                                EmbeddedTreeStructure EmbeddedStep = new()
                                                {
                                                    TreeIcon = EmbeddedTreeStructure.Icon(false),
                                                    TreeName = _origin,
                                                    IsChild = true,
                                                    IsExpand = false,
                                                    TreeParent = FindImei.ProductRelationChildTree.Last().TreeName,
                                                    ExtraBindDing = EmbeddedTreeStructure.Identity.Nonaligned
                                                };
                                                FindImei.ProductRelationChildTree.Last().ProductRelationChildTree.Add(EmbeddedStep);
                                                FindImei.ProductRelationChildTree.Last().TreeCount++;
                                            }
                                        }
                                    }
                                }
                            });
                        }
                        catch (Exception error)
                        {
                            Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
                        }
                    }

                    if (DBTYPE == DB.DB_TYPE.DB_Cloud)
                    {
                        if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                        {
                            Supabase.Postgrest.Interfaces.IPostgrestTable<TestResultRegister> queryResult = CloudDB.From<TestResultRegister>()
                             .Where(x => x.Product == product);

                            Supabase.Postgrest.Responses.ModeledResponse<TestResultRegister> Response = await queryResult.Get();

                            List<TestResultRegister> ValidDatas = [];

                            foreach (var model in Response.Models)
                            {
                                (string, DateTime) record = model.Date.ConvertDateFormat(3);
                                if (!string.IsNullOrEmpty(model.Imei) &&
                                    record.Item2 >= DateOptions.Start.ConvertDateFormat(3).Item2 &&
                                    record.Item2 <= DateOptions.End.ConvertDateFormat(3).Item2)
                                {
                                    ValidDatas.Add(model);
                                }

                                if (!HoldDateTimePush.Starts.Contains(record.Item1) && updateDate) HoldDateTimePush.Starts.Add(record.Item1);
                                if (!HoldDateTimePush.Ends.Contains(record.Item1) && updateDate) HoldDateTimePush.Ends.Add(record.Item1);
                            }

                            HoldDateTimePush.UpdateCurrent();
                            await Prepare(ValidDatas.OrderBy(x => long.Parse(x.Imei)));
                        }


                    }

                    else if (DBTYPE == DB.DB_TYPE.DB_Local)
                    {
                        string querySql = $@"SELECT * FROM testresult_register WHERE product='{product}';";
                        SqliteExceuteResult? queryResult = await DBServer.LocalDBQueryFree(querySql);

                        if (queryResult.ErrorHint == null &&
                            queryResult.Result.TryGetValue(querySql, out Dictionary<string, ICollection<object>>? dataDict) &&
                            dataDict.TryGetValue("product", out ICollection<object>? products) &&
                            dataDict.TryGetValue("process", out ICollection<object>? processs) &&
                            dataDict.TryGetValue("step", out ICollection<object>? steps) &&
                            dataDict.TryGetValue("imei", out ICollection<object>? imeis) &&
                            dataDict.TryGetValue("origin", out ICollection<object>? origins) &&
                            dataDict.TryGetValue("result", out ICollection<object>? results) &&
                            dataDict.TryGetValue("subjoin", out ICollection<object>? subjoins) &&
                            dataDict.TryGetValue("date", out ICollection<object>? dates))
                        {
                            List<TestResultRegister> ValidDatas = [];

                            for (int index = 0; index < imeis.Count; index++)
                            {
                                string _IMEI = imeis.GetSafetyChar(index).GetSafetyChar();
                                if (!string.IsNullOrEmpty(_IMEI))
                                {
                                    (string, DateTime) record = dates.GetSafetyChar(index).GetSafetyChar().ConvertDateFormat(3);
                                    if (!string.IsNullOrEmpty(_IMEI) &&
                                        record.Item2 >= DateOptions.Start.ConvertDateFormat(3).Item2 &&
                                        record.Item2 <= DateOptions.End.ConvertDateFormat(3).Item2)
                                    {

                                        TestResultRegister testResult = new()
                                        {
                                            Product = products.GetSafetyChar(index).GetSafetyChar(),
                                            Process = processs.GetSafetyChar(index).GetSafetyChar(),
                                            Step = steps.GetSafetyChar(index).GetSafetyChar(),
                                            Imei = _IMEI,
                                            Result = results.GetSafetyBool(index) ?? false,
                                            Subjoin = subjoins.GetSafetyChar(index).GetSafetyChar(),
                                            Origin = origins.GetSafetyChar(index).GetSafetyChar(),
                                            Date = dates.GetSafetyChar(index).GetSafetyChar()
                                        };
                                        if (int.TryParse(results.GetSafetyChar(index), out int reslult))
                                        {
                                            testResult.Result = reslult != 0;
                                        }
                                        ValidDatas.Add(testResult);
                                    }
                                    if (!HoldDateTimePush.Starts.Contains(record.Item1) && updateDate) HoldDateTimePush.Starts.Add(record.Item1);
                                    if (!HoldDateTimePush.Ends.Contains(record.Item1) && updateDate) HoldDateTimePush.Ends.Add(record.Item1);
                                }
                            }
                            HoldDateTimePush.UpdateCurrent();
                            await Prepare(ValidDatas.OrderBy(x => long.Parse(x.Imei)));
                        }
                    }

                    DateOptions.Query = "查询完成,更新数据";

                    _ = Task.Delay(1500).ContinueWith((task) =>
                    {
                        DateOptions.Query = "查询";
                    });

                    propertyChangeSend(nameof(HoldTestStatisticialTotal));
                });
             
                Logger.Print(RuntimeLog.LogType.Debug, "execute statistical data loader");
            }
        }

        //  测试结果数据统计 日期过滤
        private void StatiSticalDateFilterEvent(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                _= TestStatisticalLoader(HoldActivitySectionModel.ProductSelectedValuePair.Item1, HoldDateTimePush, false);
            });
        }

        //  树状图数据展开与折叠
        private void ProductTreeExtend(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                bool isExtend;
                if (VarbinProductTreeExtendText == "展开")
                {
                    VarbinProductTreeExtendText = "折叠";
                    isExtend = true;
                }
                else
                {
                    VarbinProductTreeExtendText = "展开";
                    isExtend = false;
                }

                HoldActivitySectionModel.EmbeddedIsExtend.Clear();
                var CopyExtends = HoldActivitySectionModel.EmbeddedIsExtend.ToList();
                foreach (var extend in CopyExtends)
                {
                    HoldActivitySectionModel.EmbeddedIsExtend.Add((extend.Item1, extend.Item2, extend.Item3));
                }

                Set(HoldEmbeddedTreeStructures);

                void Set(IEnumerable<EmbeddedTreeStructure> _MainTree)
                {
                    foreach (var tree in _MainTree)
                    {
                        tree.IsExpand = isExtend;
                        if (tree.ProductRelationChildTree.Count > 0)
                        {
                            foreach (var childTree in tree.ProductRelationChildTree)
                            {
                                childTree.IsExpand = isExtend;
                                if (childTree.ProductRelationChildTree.Count > 0) Set(childTree.ProductRelationChildTree);
                            }
                        }
                    }
                }
                propertyChangeSend(nameof(HoldEmbeddedTreeStructures));
            });
        }

        //  产品树选中事件
        private void ProductTreeEvent(object? param)
        {
            if (param is not null and EmbeddedTreeStructure _Tree)
            {
                string? product = null;
                string? process = null;
                string? Step = null;

                if (!string.IsNullOrEmpty(_Tree.TreeParent))
                {
                    if (_Tree.TreeParent.Contains('+'))
                    {
                        string[] _split = _Tree.TreeParent.Split('+');
                        if (_split.Length >= 2)
                        {
                            product = _split.ElementAt(0);
                            process = _split.ElementAt(1);
                            Step = _Tree.TreeName;
                        }
                    }
                    else
                    {
                        product = _Tree.TreeParent;
                        process = _Tree.TreeName;
                    }
                }
                else
                {
                    product = _Tree.TreeName;
                }

                SelectionTree.TreeProduct = product;
                SelectionTree.TreeProcess = process;
                SelectionTree.TreeStep = Step;

                SelectionTreeStdin.TreeProduct = product;
                SelectionTreeStdin.TreeProcess = process;
                SelectionTreeStdin.TreeStep = Step;
                propertyChangeSend(nameof(SelectionTree));
            }
        }

        //  加载Mes接口附加配置
        private async void LoadLocalMesConfigMap()
        {
            ICollection<KvpGroup> LocalMesMapCache = await HoldMesResportServer.RealLocalProcessMap();
            Logger.Print(RuntimeLog.LogType.Info, $"read local mes config map, where map size: {LocalMesMapCache.Count}");
            foreach (var _struct in LocalMesMapCache)
            {
                if (!string.IsNullOrEmpty(HoldActivitySectionModel.ProductSelectedValuePair.Item2) &&
                    _struct.SHowyDatas.Count >= 4)
                {
                    string process = HoldActivitySectionModel.ProductSelectedValuePair.Item2;

                    if (process == _struct.SHowyDatas.ElementAt(0).Content)
                    {

                        HoldActivitySectionModel.MesConfigMap[_struct.SHowyDatas.ElementAt(0).Content] = _struct; //  MES报告判断依据
                        HoldMesargGroups.WorkProcedure = _struct.SHowyDatas.ElementAt(1).Content; //  UI展示
                        HoldMesargGroups.StationName = _struct.SHowyDatas.ElementAt(2).Content; //  UI展示

                        propertyChangeSend(nameof(HoldMesargGroups));
                        Logger.Print(RuntimeLog.LogType.Debug, $"MesConfigMap info load, key -> {_struct.SHowyDatas.ElementAt(3).Content} value -> {_struct.SHowyDatas.ElementAt(3).Content}");
                        break;
                    }
                }
            }
        }

        //  打开Mes工位工序配置组件
        private void MesMapOpenEvent(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(async () =>
            {
                if (VarbinVsstMesMap)
                {
                    VarbinVsstMesMap = false;
                }
                
                else
                {
                    if (!string.IsNullOrEmpty(HoldActivitySectionModel.ProductSelectedValuePair.Item1))
                    {
                        //  获取工序列表
                        List<string> Processs = [];

                        foreach (var pair in ProductSelectItemPair)
                        {
                            if (pair.Key.Name == HoldActivitySectionModel.ProductSelectedValuePair.Item1)
                            {
                                Processs = [.. pair.Value.Select(x => x.Name)];
                            }
                        }
                        //  读取配置信息，并处理一些配置异常情况，包括配置key缺失，配置value不完整，意外为空的情况
                        ICollection<KvpGroup> LocalMesMapCache = await HoldMesResportServer.RealLocalProcessMap();

                        foreach(var i in LocalMesMapCache)
                        {
                            foreach(var sec in i.SHowyDatas)
                            {
                                if (sec.Flag == MesResportServer.ElementName.TestProcessName)
                                {
                                    sec.Selects = Processs;
                                }
                                
                                else if (sec.Flag == MesResportServer.ElementName.MesBingDingType)
                                {
                                    sec.Selects = HoldMesResportServer.BindingTypes;
                                }
                            }
                        }

                        HoldDesertedOptions.IFLoadMesMapInfoPush = LocalMesMapCache;
                        VarbinVsstMesMap = true;
                    }
                }
            });
        }

        //  打开/关闭指令观察配置界面
        private void StalkerStepOpenEvent(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                if (VarbinVsstStalker)
                {
                    VarbinVsstStalker = false;

                    string StalkerJson = JsonSerializer.Serialize(HoldStalkerStepTemplate, Function.SafetyReferenceJsonOptions);

                    _= IOServer.WriteAsync(LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.Stalker, 
                                            $"{ConvertFlag(HoldStalkerStepTemplate.SelectFlag).ElementAt(0)}_Stalker"),
                                            StalkerJson);
                }
                else
                {
                    VarbinVsstStalker = true;
                    HoldStalkerStepTemplate.LoderProductFlag();
                }
            });
        }

        //  产品标识变更配置更新
        private void StalkerFlagChangeEvent(object? param)
        {
            if (param is not null and string _flag)
            {
                Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    if (_flag != HoldActivitySectionModel.StalkerPreviousFlag)
                    {
                        ICollection<ProductFlag> productFlags = StalkerStepTemplate.ConvertFlag(_flag);

                        if (productFlags.Count == 1)
                        {
                            HoldStalkerStepTemplate.LoaderCommand(productFlags.ElementAt(0));
                            StalkerLoacalDataLoader(productFlags.ElementAt(0));

                            HoldActivitySectionModel.StalkerPreviousFlag = _flag;
                        }
                    }
                });
            }
        }

        //  产品标识变更本地数据加载
        private async void StalkerLoacalDataLoader(ProductFlag supormentName)
        {
            string path = LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.Stalker, $"{supormentName}_Stalker");
            try
            {
                string? LocalStalker = await IOServer.ReadAsync(path);
                if (LocalStalker is not null && !string.IsNullOrEmpty(LocalStalker.Trim()))
                {
                    StalkerStepTemplate? Templates = System.Text.Json.JsonSerializer.Deserialize<StalkerStepTemplate>(LocalStalker, Function.SafetyReferenceJsonOptions);

                    if (Templates is not null)
                    {
                        HoldStalkerStepTemplate.Templates.Clear();

                        HoldStalkerStepTemplate.Templates.AddRange(Templates.Templates);

                        //  留数据
                        HoldActivitySectionModel.ProductStalkerMap[supormentName] = [.. HoldStalkerStepTemplate.Templates];
                    }
                }
            } 
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"StalkerLoacalDataLoader Error: {error.Message} clearing this now, please reset it");
                HoldStalkerStepTemplate.Templates.Clear();
                File.Delete(path);
            }
        }

        //  删除属性监控数据
        private void StalkerStepTakeEvent(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                if (param is not null and int _index)
                {
                    HoldStalkerStepTemplate.Templates.RemoveAt(_index);
                }
            });
        }

        //  属性监控 按钮功能添加
        private void StalkerStepBfAddEvent(object? param)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (param is not null and int _index)
                {
                    if (HoldStalkerStepTemplate.Templates.Count > _index)
                    {
                        HoldStalkerStepTemplate.Templates[_index].ButActions.Add(new ButtomFunc());
                    }
                }
            });
        }

        //  属性监控 按钮功能删除
        private void StalkerStepBfTakeEvent(object? param)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (param is not null and string _InfoGroups)
                {
                    string[] Datas = RegExp.RegExpEmpty().Split(_InfoGroups);

                    if (Datas.Length >= 2 &&
                        int.TryParse(Datas.ElementAt(0).GetSafetyChar(), out int _innerinde) &&
                        int.TryParse(Datas.ElementAt(1).GetSafetyChar(), out int _outindex))

                        if (HoldStalkerStepTemplate.Templates.Count > _outindex)
                        {
                            HoldStalkerStepTemplate.Templates[_outindex].ButActions.RemoveAt(_innerinde);
                        }
                }
            });
        }

        //  工单导入
        private async void WorkOrderImport()
        {
            static (bool?, string[]) IP_AccessLocalFile()
            {
                OpenFileDialog FileSelector = new()
                {
                    DefaultDirectory = "dir".CurrentDir(),
                    Filter = "Excel Files (*.xlsx, *.xls, *.csv)|*.xlsx;*.xls;*.csv|All Files (*.*)|*.*",
                    Multiselect = true
                };

                bool? _Show = FileSelector.ShowDialog();
                string[] _File = FileSelector.FileNames;
                return (_Show, _File);
            }

            (bool?, string[]) LocalFileInfos = IP_AccessLocalFile();

            Excel excel = new(HoldActivitySectionModel.DBWorkOrderMap, DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Cloud);

            bool RunningToken = true;

            if (LocalFileInfos.Item1 is not null and bool _bool && _bool)
            {
                Action<double, string?> LoaderProcess = await CustomMessageBox.Show(new CustomMessageBox.ShowyPrograssSetting());
                excel.ReadExcelAsync(LocalFileInfos.Item2,
                async (Workorders) =>
                {
                    if (Workorders.Any())
                    {
                        if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Cloud)
                        {
                            if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                            {
                                foreach (var workorder in Workorders)
                                {

                                    var queryResult = await CloudDB.From<WorkOrderPreview>()
                                        .Select(x => new object[] { x.WorkorderNum })
                                        .Where(x => x.WorkorderNum == workorder).Get();

                                    if (queryResult.Model is not null)
                                    {
                                        var question = await CustomMessageBox.Show(
                                            new CustomMessageBox.InquiryNmPopupSetting 
                                            { 
                                                Msg_Title = "提示", 
                                                Msg_BodyText = $"已存在工单 {Workorders.Join("\n")}，是否重新导入", 
                                                Msg_InquiryButtoms = ["取消导入", "覆盖导入"],
                                                Msg_WinWidth = 450,
                                                Msg_WinHeight = 210
                                            });

                                        if (question.index == 1)
                                        {
                                            await CloudDB.From<WorkOrderPreview>().Where(x => x.WorkorderNum == workorder).Delete();
                                            await CloudDB.From<WorkOrderUnfold>().Where(x => x.WorkorderNum == workorder).Delete();
                                            Logger.Print(RuntimeLog.LogType.Warning, $"{nameof(WorkOrderImport)} cloud cover");
                                        }
                                        else
                                        {
                                            RunningToken = false;
                                        }
                                    }
                                }
                            }
                        }

                        else if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Local)
                        {
                            string combination = Workorders.Join(",", true);

                            var queryResult = await DBServer.LocalDBQueryFree($"SELECT * FROM workorder_preview WHERE workorder_num in ({combination})");

                            if (queryResult.Result.Count > 0)
                            {
                                var question = await CustomMessageBox.Show(
                                    new CustomMessageBox.InquiryNmPopupSetting
                                    {
                                        Msg_Title = "提示",
                                        Msg_BodyText = "已存在工单，是否重新导入",
                                        Msg_InquiryButtoms = ["取消导入", "覆盖导入"]
                                    });

                                if (question.index == 1)
                                {
                                    await DBServer.LocalDBQueryFree($"DELETE FROM workorder_preview WHERE workorder_num in ({combination})");
                                    await DBServer.LocalDBQueryFree($"DELETE FROM workorder_unfold WHERE workorder_num in ({combination})");
                                    Logger.Print(RuntimeLog.LogType.Warning, $"{nameof(WorkOrderImport)} local cover");
                                }
                                else
                                {
                                    RunningToken = false;
                                }
                            }
                        }
                    }
                    return RunningToken;
                },
                (process, hint) =>
                {
                    LoaderProcess.Invoke(process, hint);
                },
                async (isCloud, unfold, preview) =>
                {
                    if (isCloud)
                    {
                        if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB &&
                            unfold is List<WorkOrderUnfold> _unfold &&
                            preview is List<WorkOrderPreview> _prview && RunningToken)
                        {
                            try
                            {
                                Logger.Print(RuntimeLog.LogType.Debug, "start cloud db insert from excel");

                                await CloudDB.From<WorkOrderUnfold>().Insert(_unfold);

                                await CloudDB.From<WorkOrderPreview>().Insert(_prview);
                            } 
                            catch (Exception error)
                            {
                                Logger.Print(RuntimeLog.LogType.Fatal, $"order import error: {error.Message}");
                            }
                        }
                    }
                    else
                    {
                        if (unfold is List<string> _unfold &&
                            preview is List<string> _prview &&
                            RunningToken)
                        {
                            Logger.Print(RuntimeLog.LogType.Debug, "start local db insert from excel");

                            await DBServer.LocalDBQuery(_unfold);

                            await DBServer.LocalDBQuery(_prview);
                        }
                    }
                },
                async () =>
                {
                    await CustomMessageBox.Show(
                             new CustomMessageBox.InquiryNmPopupSetting
                             {
                                 Msg_Title = "询问",
                                 Msg_InquiryIcon = 0,
                                 Msg_BodyText = "\n1.请检查所选工序是否正确，因为这关乎数据库字段映射数据的加载，数据无法映射导致工单获取失败" +
                                                "\n2.请检查文档是否有乱码或数据意外被清空了导致工单获取失败",
                                 Msg_InquiryButtoms = ["知道了"],
                                 Msg_HAlignment = System.Windows.HorizontalAlignment.Left,
                                 Msg_WinWidth = 500,
                                 Msg_WinHeight = 300
                             });

                    LoaderProcess(100.0, "发生错误，结束当前导入任务");
                });
            }
        }

        //  注册产品和工序 - 退出
        private void RegisterCancelEvent(object? param)
        {
            UIload(Interfacial.PRDTProductOutTextBox);
        }

        //  注册产品和工序 - 提交
        private void RegisterAcceptEvent(object? param)
        {
            try
            {
                RegisterExcuteSave(VarbinRegProductContent, VarbinRegProcessContent, HoldActivitySectionModel.RegisterIsSecondaryKey);
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  注册产品和工序 - 执行
        private async void RegisterExcuteSave(string product, string process, int ischild, bool SkipCheck = false)
        {
            DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));
            
                //  数据可录入检查
                bool baseVerify(ICollection<object> products, ICollection<object> processs)
                {
                    //  为空检查
                    if (string.IsNullOrEmpty(VarbinRegProductContent))
                    {
                        VarbinRegChildKeyHint = "主键不可为空";
                        return false;
                    }
                    else if (HoldActivitySectionModel.RegisterIsSecondaryKey == 1 && 
                             string.IsNullOrEmpty(VarbinRegProcessContent))
                    {
                        VarbinRegChildKeyHint = "子键不可为空";
                        return false;
                    }

                    //  检查主键索引
                    if (products.Contains(VarbinRegProductContent))
                    {
                        //  添加子键时，检查子键是否存在
                        if (HoldActivitySectionModel.RegisterIsSecondaryKey == 1)
                        {
                            int index = 0;
                            bool state = true;
                            foreach (var prd in products)
                            {
                                if (prd.Equals(VarbinRegProductContent.Trim()))
                                {

                                    if (processs.Contains(VarbinRegProcessContent) &&
                                        index == processs.IndexOf(VarbinRegProcessContent))
                                    {
                                        state = false;
                                        VarbinRegChildKeyHint = "子键已存在";
                                        break;
                                    }
                                }
                                index++;
                            }
                            return state;
                        }
                        else//  添加主键时，检查子键是否存在
                        {
                            bool state = true;
                            int index = 0;
                            foreach (var prd in products)
                            {
                                if (prd.Equals(VarbinRegProductContent.Trim()))
                                {
                                    if (string.IsNullOrEmpty(processs.ElementAt(index).GetSafetyChar()))
                                    {
                                        VarbinRegChildKeyHint = "主键已存在";
                                        state = false;
                                        break;
                                    }
                                }
                                index++;
                            }
                            return state;
                        }
                    }
                    else
                    {
                        return true;
                    }
                }

            if (DBTYPE == DB.DB_TYPE.DB_Cloud)
            {
                if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                {
                    var queryResult = await CloudDB.From<ProductConfigRelation>()
                        .Select(x => new object[] { x.PrdId, x.PrdName, x.PrdProcess })
                        .Get();

                    List<object> ids = [.. queryResult.Models.Select(x => (object)x.PrdId)];
                    List<object> products = [.. queryResult.Models.Select(x => (object)x.PrdName)];
                    List<object> processs = [.. queryResult.Models.Select(x => (object)x.PrdProcess)];

                    bool canExecbute = baseVerify(products, processs);

                    if (canExecbute || SkipCheck)
                    {
                        string idkey = ids.GetDesorderly();
                        ProductConfigRelation insertData = new()
                        {
                            PrdId = idkey,
                            PrdName = product,
                            PrdProcess = process,
                            PrdTreeKey = ischild,
                            PrdApply = 0
                        };

                        var InsertResponse = await CloudDB.From<ProductConfigRelation>().Insert(insertData);

                        if (InsertResponse.ResponseMessage is not null &&
                            InsertResponse.ResponseMessage.IsSuccessStatusCode)
                        {
                            VarbinRegChildKeyHint = "键值添加成功";

                            Logger.Print(RuntimeLog.LogType.Debug, $"info write to sql success, where prd {VarbinRegProductContent}");
                        }
                    }
                }

            }

            else if (DBTYPE == DB.DB_TYPE.DB_Local)
            {
                async void insertSqlExecute(string idkey)
                {
                    string insertCommandSql = $"INSERT INTO product_config_relation VALUES(" +
                                              $"'{idkey}'," +
                                              $"'{product}'," +
                                              $"'{process}'," +
                                              $"{ischild}," +
                                              $"{0})";

                    if (!string.IsNullOrEmpty(insertCommandSql) && await DBServer.LocalDBQueryFree(insertCommandSql) != null)
                    {
                        VarbinRegChildKeyHint = "键值添加成功";
                        GetProductInfos();
                        Logger.Print(RuntimeLog.LogType.Debug, $"info write to sql success, where prd {VarbinRegProductContent}");
                    }
                }

                string queryCommandSql = $"SELECT * FROM product_config_relation";

                if (await DBServer.LocalDBQueryFree(queryCommandSql) is var queryResult &&
                    queryResult.ErrorHint == null)
                {
                    if (queryResult.ErrorHint == null &&
                        queryResult.Result.TryGetValue(queryCommandSql, out Dictionary<string, ICollection<object>>? dataDict) &&
                        dataDict.TryGetValue("prd_id", out ICollection<object>? Ids) &&
                        dataDict.TryGetValue("prd_name", out ICollection<object>? Products) &&
                        dataDict.TryGetValue("prd_process", out ICollection<object>? Processs))
                    {
                        bool canExecbute = baseVerify(Products, Processs);
                        string idkey = Ids.GetDesorderly(); //  根据已有的ID，生成可用ID
                        if (canExecbute || SkipCheck) insertSqlExecute(idkey);
                    }
                    else
                    {
                        string idkey = 2.GetDesorderly();
                        insertSqlExecute(idkey);
                    }
                }

            }
            await Task.Delay(1400).ContinueWith((task) =>
            {
                VarbinRegChildKeyHint = "是否子键";

                GetProductInfos();

            }).ConfigureAwait(true);
            
        }

        //  获取配置信息
        private async void GetConfigInfos(string product, string process)
        {
            async Task GetActivityListItem()
            {
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    try
                    {
                        if (SupplementConfigListItems.Any()) SupplementConfigListItems.Clear();

                        ICollection<TestItemDeepSeatedSealed> OrderbyConfigItems = [.. ActivityConfigListItems.OrderBy(x => x.Priority)];

                        ActivityConfigListItems.Reteller(OrderbyConfigItems);

                        List<TestItemSurfaceSealed> PriorityItemsStruct = [];
                        foreach (TestItemDeepSeatedSealed item in ActivityConfigListItems.Where(x => x.Status))
                        {
                            PriorityItemsStruct.Add(new TestItemSurfaceSealed(item.Step, "MustardPop".FindSolidBrush()));

                            foreach (var field in item.GetFields())
                            {
                                string? value = field.GetValue(item)?.GetSafetyChar();
                                if (!string.IsNullOrEmpty(value) && value.Contains("DEF:"))
                                {
                                    string realValue = value.Replace("DEF:", "");
                                    Dictionary<int, string> Matchs = realValue.MatchAll("\\{(.*?)\\}", 1);
                                    if (Matchs.Count > 0)
                                    {
                                        foreach (var kvp in Matchs)
                                        {
                                            SupplementConfigListItems.Add(new SupplementConfig
                                            {
                                                Name = kvp.Value,
                                                Step = item.Step
                                            });
                                        }
                                    }
                                }
                            }
                        }

                        if (SupplementConfigListItems.Any())
                        {
                            SupplementConfigListItems.Last().DelBorder = true;
                        }

                        ActivityExpoListItems.Reteller(PriorityItemsStruct);

                        if (VarbinUIBind.UIType == Interfacial.PRDTAttributeConfig)
                        {
                            HoldDesertedOptions.IFLoadAttrItemsAddPush = [.. ActivityConfigListItems];
                        }
                    }
                    catch (Exception error)
                    {
                        Logger.Print(RuntimeLog.LogType.Debug, $"Priority collection from configural: {error.Message}");
                    }
                });
            }

            try
            {
                DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));

                if (DBTYPE == DB.DB_TYPE.DB_Cloud)
                {
                    if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                    {
                        string code = CryptServer.ENbase64(product + process);

                        var queryResult = await CloudDB.From<ProductConfigField>()
                            .Where(x => x.Code == code)
                            .Get();

                        Logger.Print(RuntimeLog.LogType.Debug, $"find code {code} in config table");

                        if (queryResult.Models.Count == 1 && queryResult.Model is not null)
                        {
                            List<TestItemDeepSeatedSealed>? DejsonCollection = JsonSerializer.Deserialize<List<TestItemDeepSeatedSealed>>(
                                                            queryResult.Model.FieldJson, Function.SafetyReferenceJsonOptions);
                            if (DejsonCollection is not null)
                            {
                                ActivityConfigListItems.Reteller(DejsonCollection);
                            }

                            await GetActivityListItem();
                        }

                        else
                        {
                            if (queryResult.Models.Count == 0)
                            {
                                ActivityConfigListItems.Clear();
                                ActivityExpoListItems.Clear();
                                propertyChangeSend(nameof(ActivityExpoListItems));
                                Logger.Print(RuntimeLog.LogType.Warning, $"{MethodBase.GetCurrentMethod()?.Name} config groups is empty");
                            }
                            else if (queryResult.Models.Count > 1)
                            {
                                await CustomMessageBox.Show(
                                    new CustomMessageBox.InquiryNmPopupSetting
                                    {
                                        Msg_Title = "警告",
                                        Msg_BodyText = $"存在{queryResult.Models.Count}条数据",
                                        Msg_InquiryButtoms = ["知道了"]
                                    });
                            }
                        }
                    }
                }

                else if (DBTYPE == DB.DB_TYPE.DB_Local)
                {
                    string queryConfigSql = $"SELECT * FROM product_config_field WHERE field_product='{product}' and field_process='{process}'";

                    SqliteExceuteResult queryResult = await DBServer.LocalDBQueryFree(queryConfigSql);

                    if (queryResult.ErrorHint == null &&
                        queryResult.Result.TryGetValue(queryConfigSql, out Dictionary<string, ICollection<object>>? ConfigDict))
                    {
                        if (ConfigDict is not null &&
                            ConfigDict.Count > 0 &&
                            ConfigDict.TryGetValue("field_json", out ICollection<object>? fieldJson))
                        {
                            await Task.Run(async () =>
                            {
                                if (fieldJson.Count == 1)
                                {
                                    List<TestItemDeepSeatedSealed>? DejsonCollection = JsonSerializer.Deserialize<List<TestItemDeepSeatedSealed>>(
                                                                    fieldJson.ElementAt(0).GetSafetyChar(), Function.SafetyReferenceJsonOptions);
                                    if (DejsonCollection is not null)
                                    {
                                        ActivityConfigListItems.Reteller(DejsonCollection);
                                    }
                                    await GetActivityListItem();
                                }
                                else
                                {
                                    if (fieldJson.Count == 0)
                                    {
                                        ActivityConfigListItems.Clear();
                                        ActivityExpoListItems.Clear();
                                    }
                                    else if (fieldJson.Count > 1)
                                    {
                                        await CustomMessageBox.Show(
                                            new CustomMessageBox.InquiryNmPopupSetting
                                            {
                                                Msg_Title = "警告",
                                                Msg_BodyText = $"存在{fieldJson.Count}条配置数据",
                                                Msg_InquiryButtoms = ["知道了"]
                                            });
                                    }
                                }
                            });
                        }
                        else
                        {
                            ActivityConfigListItems.Clear();
                            ActivityExpoListItems.Clear();
                        }
                    }
                    else
                    {
                        ActivityConfigListItems.Clear();
                        ActivityExpoListItems.Clear();
                    }
                }
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  加载配置固定选项
        private void LoadCondigOptions()
        {
            Application.Current.Dispatcher.InvokeAsync(async () =>
            {
                ConfigurableSelectItems.Clear();
                ConfigurableSelectItemPair.Clear();
                 foreach (var kvp in ActivityAssistBehivor.Behivor.ConfigFixedOpptions)
                 {
                    if (kvp.Key.Name == "导入配置")
                    {
                        object? AssemblyCollection = await IOServer.GetAssembly(); //  空参数，返回配置文件名
                        if (AssemblyCollection is not null and List<string> _AssemblyNames)
                        {
                            foreach (var name in _AssemblyNames)
                            {
                                KeyValuePairSealed _KeyValuePairItem = new("\ue615", name, "BurgundyNight".FindSolidBrush());

                                if (ConfigurableSelectItemPair.TryGetValue(kvp.Key, out ObservableCollection<KeyValuePairSealed>? _value))
                                {
                                    _value.Add(_KeyValuePairItem);
                                }
                                else
                                {
                                    ConfigurableSelectItemPair.Add(kvp.Key, [_KeyValuePairItem]);
                                }

                                string FullPath = System.IO.Path.Combine("MyConfig".CurrentDir(), "DefaultConfig", name);

                                if (!IOServer.IsFile(FullPath))
                                {
                                    IOServer.CreateFile(FullPath);

                                    object? DefaultConfig = await IOServer.GetAssembly(name);

                                    if (DefaultConfig is not null and string _ConfigContent)
                                    {
                                        await IOServer.WriteAsync(FullPath, _ConfigContent);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        //  之前不执行的代码为TryValue的out对象添加的数据，并且之前并没有clear，造成了某种UI堵塞的现象，并不是ConfigurableSelectItems的数据问题 
                        #pragma warning disable CA1854
                        if (ConfigurableSelectItemPair.ContainsKey(kvp.Key)) 
                        {
                            ConfigurableSelectItemPair[kvp.Key].AddRange(kvp.Value);
                        }
                        else
                        {
                            ConfigurableSelectItemPair.Add(kvp.Key, kvp.Value);
                        }
                    }
                    ConfigurableSelectItems.Add(kvp.Key);
                 }

                 propertyChangeSend(nameof(ConfigurableSelectItems));
                 propertyChangeSend(nameof(ConfigurableSelectItemPair));
            });
        }

        //  获取产品和工序
        private void GetProductInfos(Action? LoadCompeledCallBack = null)
        {
            try
            {
                var ProducrExecute = new Product(DBServer, IOServer, CryptServer);

                ProducrExecute.LoadProduct(
                    () =>
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            ProductSelectItems.Reteller(ActivityAssistBehivor.Behivor.ProductFixedOpptions.Keys);

                            LeisureProducts.Clear();

                            HoldEmbeddedTreeStructures.Clear();
                        });
                    },
                    (product, process) =>
                    {
                        GetConfigInfos(product, process); //  符合应用 + 有子项的情况，加载配置文件

                        HoldActivitySectionModel.ProductSelectedValuePair = (product, process);

                        Task.Delay(2000).ContinueWith(async (task) =>
                        {
                            await TestStatisticalLoader(HoldActivitySectionModel.ProductSelectedValuePair.Item1, HoldDateTimePush, true);

                            //  查看是否包含当前日期的选项，没有则手动补上，后续加载详情界面时不再加载该日期数据，防止破坏选项数据
                            string dateNow = DateTime.Now.ToString(HoldDateTimePush.TimeFormat);
                            if (!HoldDateTimePush.Ends.Contains(dateNow))
                            {
                                HoldDateTimePush.Ends.Add(dateNow);
                            }
                        });
                    },
                    (selectitem) =>
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            ProductSelectItems.Add(selectitem);

                            LeisureProducts.Add(selectitem.Name);
                        });
                    },
                    () =>
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            ActivityConfigListItems.Clear();
                            ActivityExpoListItems.Clear();
                        });
                    },
                    (product) =>
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            VarbinRegProductContent = product;

                            ProductSubjoinAssert(product);
                        });
                    },
                    (selectechoitems) =>
                    {
                        ProductSelectedValue = [.. selectechoitems]; //  作为按钮默认显示项

                        GetDBfieldMapInfos();
                    },
                    async (classify) =>
                    {
                        Dictionary <KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>> NewSelectPair = [];

                        //  使用新集合加载固定项，避免数据污染
                        foreach (var pair in ActivityAssistBehivor.Behivor.ProductFixedOpptions)
                        {
                            NewSelectPair.Add(pair.Key, pair.Value);
                        }

                        int index = 0;
                        foreach (var SelectItem in ProductSelectItems.ToList())
                        {
                            bool ProductMatchSwitch = false;
                            //  进行分类
                            foreach (var pair in classify)
                            {
                                if (SelectItem.Name == pair.Key)
                                {
                                    ObservableCollection<KeyValuePairSealed> ValueItems = [.. pair.Value.Select(name => new KeyValuePairSealed("\ue691", name))];

                                    NewSelectPair.TryAdd(SelectItem, ValueItems);

                                    //  添加产品预览- 产品 -> 工序
                                    List<EmbeddedTreeStructure> ProcessStructs = [];

                                    EmbeddedTreeStructure ProductStruct = new ()
                                    {
                                        TreeIcon = EmbeddedTreeStructure.Icon(),
                                        TreeName = SelectItem.Name,
                                        TreeCount = ValueItems.Count,
                                        IsChild = false,
                                        IsExpand = await ProductExtendSample(string.Empty, SelectItem.Name)
                                    };

                                    foreach (var item in ValueItems)
                                    {
                                        EmbeddedTreeStructure ProcessStruct = new()
                                        {
                                            TreeIcon = EmbeddedTreeStructure.Icon(false),
                                            TreeName = item.Name,
                                            IsChild = true,
                                            TreeParent = SelectItem.Name,
                                            IsExpand = await ProductExtendSample(string.Empty, SelectItem.Name)
                                        };

                                        ProcessStructs.Add(ProcessStruct);
                                    }

                                    ProductStruct.ProductRelationChildTree = ProcessStructs;

                                    Application.Current.Dispatcher.Invoke(() =>
                                    {
                                        HoldEmbeddedTreeStructures.Add(ProductStruct);

                                        SelectItem.Visibility = Visibility.Visible;

                                        ProductSelectItems[index] = SelectItem;
                                    });

                                    ProductMatchSwitch = true;
                                    break;
                                }
                            }
                            if (!ProductMatchSwitch) //  分支集合与主集合没有产生匹配时，也要添加一个产品名称作为展示
                            {
                                if (!ActivityAssistBehivor.Behivor.ProductFixedOpptions.Keys.Select(x => x.Name).Contains(SelectItem.Name))
                                {
                                    Application.Current.Dispatcher.Invoke(() =>
                                    {
                                        HoldEmbeddedTreeStructures.Add(new EmbeddedTreeStructure
                                        {
                                            TreeIcon = EmbeddedTreeStructure.Icon(),
                                            TreeName = SelectItem.Name,
                                            TreeCount = 0,
                                            IsChild = false,
                                            IsExpand = false
                                        });
                                    });
                                }
                            }
                            index++;
                        }

                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            ProductSelectItemPair = NewSelectPair;
                        });
                    });

                LoadCompeledCallBack?.Invoke();

                Logger.Debug($"product infos dispose complete");
           
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  产品附加判断
        private void ProductSubjoinAssert(string product)
        {
            //  添加产品类型标识
            foreach (var kvp in ActivityAssistBehivor.Behivor.ProductFlagChzMap)
            {
                if (product.Contains(kvp.Value))
                {
                    HoldActivitySectionModel.CurrentProductFlag = kvp.Key;
                    ActivityDetetor.SetMainAccording($"{kvp.Key}");
                    StalkerLoacalDataLoader(kvp.Key);
                }
            }

            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                //  判断是否需要展示MES参数信息
                if (product.Contains("独立网关"))
                {
                    VarbinVsstMesFace = true;
                    VarbinVsstMesFace = true;
                    HoldActivitySectionModel.TestDemandType = DemandType.Mes;
                    HoldMesResportServer.EchoMesinLoacal((_apiUrl) =>
                    {
                        MesargPushUrl = _apiUrl;
                        LoadLocalMesConfigMap();
                        propertyChangeSend(nameof(HoldMesargGroups));

                    });
                }
                
                else
                {
                    VarbinVsstMesFace = false;
                    VarbinVsstMesFace = false;
                    HoldActivitySectionModel.TestDemandType = DemandType.Invalid;
                }
            });
        }

        //  获取数据库字段映射
        private void GetDBfieldMapInfos(ICollection<string>? columns = null)
        {
            try
            {
                HoldActivitySectionModel.DBWorkOrderMap.Clear();

                Application.Current.Dispatcher.Invoke(async () => 
                {
                    if (!string.IsNullOrEmpty(HoldActivitySectionModel.ProductSelectedValuePair.Item1))
                    {
                        //  已解决问题: 直接使用ProductSelectedValue而不是HoldActivitySectionModel.ProductSelectedValue，导致选择了无效项，查询结果为空，但是
                        //  columns非null，映射界面有下拉数据的问题，使用HoldActivitySectionModel.ProductSelectedValue可以过滤无效项
                        string product = HoldActivitySectionModel.ProductSelectedValuePair.Item1;

                        DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));

                        if (DBTYPE == DB.DB_TYPE.DB_Cloud)
                        {
                            if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                            {
                                //  查询映射,反序列化缓存数据
                                var queryResult = await CloudDB.From<DbFieldRelation>().Where(x => x.ProductName == product).Get().ConfigureAwait(false);

                                if (queryResult.Model is not null)
                                {
                                    HoldActivitySectionModel.CusultColumnNames = [.. RegExp.RegExpMultiSpacing().Split(queryResult.Model.ConsultColumns)];

                                    WorkOrderFieldMapSealed? relation = JsonSerializer.Deserialize<WorkOrderFieldMapSealed>(queryResult.Model.FieldJson,
                                                                        Function.SafetyReferenceJsonOptions);

                                    if (relation is not null)
                                    {
                                        foreach (var field in relation.GetPropertys(1))
                                        {
                                            object? value = field.GetValue(relation);
                                            if (value is not null)
                                            {
                                                HoldActivitySectionModel.DBWorkOrderMap.Add(field.Name, value.GetSafetyChar());
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    if (columns is not null && columns.Count > 0)
                                    {
                                        HoldActivitySectionModel.CusultColumnNames = columns;
                                        HoldActivitySectionModel.DBWorkOrderMap = [];
                                    }
                                }
                            }
                        }

                        else if (DBTYPE == DB.DB_TYPE.DB_Local)
                        {
                            string queryConfigSql = $"SELECT consult_columns, field_json FROM dbfield_relation WHERE prd_name='{product}'";
                            if (await DBServer.LocalDBQueryFree(queryConfigSql) is var queryResult)
                            {
                                if (queryResult.ErrorHint == null &&
                                    queryResult.Result.TryGetValue(queryConfigSql, out Dictionary<string, ICollection<object>>? ConfigDict))
                                {

                                    if (ConfigDict is not null &&
                                        ConfigDict.TryGetValue("consult_columns", out ICollection<object>? ConsultColumns) &&
                                        ConfigDict.TryGetValue("field_json", out ICollection<object>? FieldJsons))
                                    {
                                        if (ConsultColumns is not null)
                                        {
                                            if (columns is not null && columns.Count > 0)
                                            {
                                                HoldActivitySectionModel.CusultColumnNames = columns;
                                            }
                                            else
                                            {
                                                HoldActivitySectionModel.CusultColumnNames = [.. RegExp.RegExpMultiSpacing().Split(ConsultColumns.ElementAt(0).GetSafetyChar())];
                                            }
                                            WorkOrderFieldMapSealed? relation = JsonSerializer.Deserialize<WorkOrderFieldMapSealed>(FieldJsons.ElementAt(0).GetSafetyChar());
                                            if (relation is not null)
                                            {
                                                foreach (var field in relation.GetPropertys(1))
                                                {
                                                    object? value = field.GetValue(relation);
                                                    if (value is not null)
                                                    {
                                                        if (HoldActivitySectionModel.DBWorkOrderMap.ContainsKey(field.Name))
                                                        {
                                                            HoldActivitySectionModel.DBWorkOrderMap[field.Name] = value.GetSafetyChar();
                                                        }
                                                        else
                                                        {
                                                            HoldActivitySectionModel.DBWorkOrderMap.Add(field.Name, value.GetSafetyChar());
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (columns is not null && columns.Count > 0)
                                        {
                                            HoldActivitySectionModel.CusultColumnNames = columns;
                                            HoldActivitySectionModel.DBWorkOrderMap = [];
                                        }
                                    }
                                }
                                else
                                {
                                    if (columns is not null && columns.Count > 0)
                                    {
                                        HoldActivitySectionModel.CusultColumnNames = columns;
                                        HoldActivitySectionModel.DBWorkOrderMap = [];
                                    }
                                }
                            }
                        }
                    }
          
                    KeyValuePair<Dictionary<string, string>, ICollection<string>> infoGrounp = new(HoldActivitySectionModel.DBWorkOrderMap,
                                                                                                   HoldActivitySectionModel.CusultColumnNames);

                    HoldDesertedOptions.IFLoadDBMapInfoPush = infoGrounp;
                    Logger.Print(RuntimeLog.LogType.Debug, $"dbfield map Infos load finish and map ui state: {VarbinUIBind.UIType}");

                }, DispatcherPriority.Background);
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  处理数据库映射数据
        private void CaptrueDBrelation(object? param)
        {
            try
            {
                if (param is not null and Dictionary<string, string> translations)
                {
                    string Jsonserial = JsonSerializer.Serialize<dynamic>(translations, Function.SafetyReferenceJsonOptions);

                    Thread Thread = new(async () =>
                    {
                        string? product = HoldActivitySectionModel.ProductSelectedValuePair.Item1;
                        if (!string.IsNullOrEmpty(product))
                        {
                            DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));

                            if (DBTYPE == DB.DB_TYPE.DB_Cloud)
                            {
                                DbFieldRelation insertData = new()
                                {
                                    ProductName = product,
                                    FieldJson = Jsonserial,
                                    ConsultColumns = HoldActivitySectionModel.CusultColumnNames.Join(" && ")
                                };

                                if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB &&
                                    product is not null)
                                {
                                    async Task DisposeFieldAlter()
                                    {
                                        var queryResult = await CloudDB.From<DbFieldRelation>().Where(x => x.ProductName == product).Get();

                                        if (queryResult.Models is not null && queryResult.Models.Count > 0)
                                        {
                                            await CloudDB.From<DbFieldRelation>()
                                            .Set(x => x.FieldJson, Jsonserial)
                                            .Where(x => x.ProductName == product)
                                            .Update();
                                            Logger.Print(RuntimeLog.LogType.Debug, "execute dbmap alter");
                                        }
                                        else
                                        {
                                            await CloudDB.From<DbFieldRelation>().Insert(insertData);
                                            Logger.Print(RuntimeLog.LogType.Debug, "execute dbmap insert");
                                        }
                                    }

                                    await DBServer.CloudAnchorChannel<DbFieldRelation>(async () =>
                                    {
                                        await CustomMessageBox.Show(
                                           new CustomMessageBox.InquiryDlPopupSetting
                                           {
                                               Msg_Title = $"数据库字段映射",
                                               Msg_BodyText = "保存成功",
                                               Msg_Result = 2,
                                               Msg_DelayExitTime = 1200,
                                               Msg_WinRadius = 6
                                           });

                                        GetDBfieldMapInfos();

                                        Logger.Print(RuntimeLog.LogType.Debug, "dbmap alter success");
                                    },
                                    async () =>
                                    {
                                        await DisposeFieldAlter();
                                    });
                                }
                            }
                            else if (DBTYPE == DB.DB_TYPE.DB_Local)
                            {
                                string Sql = string.Empty;
                                var queryResult = await DBServer.LocalDBQueryFree($"SELECT * FROM dbfield_relation WHERE prd_name='{product}'");
                                if (queryResult.Result.Count > 0)
                                {
                                    Sql = $"UPDATE dbfield_relation SET " +
                                          $"consult_columns='{HoldActivitySectionModel.CusultColumnNames.Join(" && ")}'," +
                                          $"field_json ='{Jsonserial}' " +
                                          $"WHERE prd_name='{product}'";
                                }
                                else
                                {
                                    Sql = $"INSERT INTO dbfield_relation VALUES(" +
                                          $"'{product}'," +
                                          $"'{Jsonserial}'," +
                                          $"'{HoldActivitySectionModel.CusultColumnNames.Join(" && ")}')";
                                }

                                if (!string.IsNullOrEmpty(Sql) &&
                                    await DBServer.LocalDBQueryFree(Sql) is not null and SqliteExceuteResult Result &&
                                    Result.ErrorHint is null)
                                {

                                    await CustomMessageBox.Show(
                                            new CustomMessageBox.InquiryDlPopupSetting
                                            {
                                                Msg_Title = $"数据库字段映射",
                                                Msg_BodyText = "保存成功",
                                                Msg_Result = 2,
                                                Msg_DelayExitTime = 1200,
                                                Msg_WinRadius = 6
                                            });

                                    GetDBfieldMapInfos();

                                }
                            }
                        }
                        Logger.Print(RuntimeLog.LogType.Debug, $"dispose db relation, product: {product}");
                    })
                    {
                        IsBackground = true
                    };

                    Thread.Start();
                }
                return;
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  处理配置返回数据
        private void CaptrueAttribute(object? param)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                try
                {
                    string? product = HoldActivitySectionModel.ProductSelectedValuePair.Item1;
                    string? process = HoldActivitySectionModel.ProductSelectedValuePair.Item2;

                    if (param is not null and IEnumerable<TestItemDeepSeatedSealed> _TestItemDeepSeatedSealed &&
                        !string.IsNullOrEmpty(product) &&
                        !string.IsNullOrEmpty(process))
                    {
                        ActivityBackEchoListItems = [.. ActivityConfigListItems];

                        Thread Thread = new(async () =>
                        {
                            string _Json = JsonSerializer.Serialize(_TestItemDeepSeatedSealed.ToList(), Function.SafetyReferenceJsonOptions);

                            if (string.IsNullOrEmpty(_Json))
                            {
                                Logger.Information("config out infos JsonSerial fail");
                            }
                            else
                            {
                                string code = CryptServer.ENbase64(product + process);

                                Logger.Information($"save json for {product}-{process}, where code={code}");

                                Logger.Information($"echo json detail: \r\n\n{_Json}\r\n");

                                DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));

                                if (DBTYPE == DB.DB_TYPE.DB_Cloud)
                                    {
                                        if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                                        {
                                            var existsQuery = await CloudDB.From<ProductConfigField>()
                                                .Where(x => x.Code == code)
                                                .Get();

                                            async Task SaveAttribute()
                                            {
                                                if (existsQuery.ResponseMessage is not null &&
                                                    existsQuery.ResponseMessage.IsSuccessStatusCode &&
                                                    existsQuery.Model is not null && existsQuery.Models.Count == 1)
                                                {
                                                    var UpdateResponse = await CloudDB.From<ProductConfigField>()
                                                           .Set(x => x.FieldJson, _Json)
                                                           .Where(x => x.Code == code)
                                                           .Update();
                                                    Logger.Print(RuntimeLog.LogType.Warning, "cloud db config update");
                                                }
                                                else
                                                {
                                                    if (existsQuery.Models.Count == 0)
                                                    {
                                                        var InsertResponse = await CloudDB.From<ProductConfigField>()
                                                        .Insert(new ProductConfigField()
                                                        {
                                                            Code = code,
                                                            FieldJson = _Json,
                                                            FieldProcess = process,
                                                            FieldProduct = product
                                                        });
                                                        Logger.Print(RuntimeLog.LogType.Warning, "cloud db config insert");
                                                    }
                                                    
                                                    else if (existsQuery.Models.Count > 1)
                                                    {
                                                        await CustomMessageBox.Show(
                                                            new CustomMessageBox.InquiryNmPopupSetting 
                                                            { 
                                                                Msg_Title = "警告", 
                                                                Msg_BodyText = $"存在{existsQuery.Models.Count}条数据", 
                                                                Msg_InquiryButtoms = ["知道了"] 
                                                            });
                                                    }
                                                }
                                            }

                                            await DBServer.CloudAnchorChannel<ProductConfigField>(() =>
                                            {
                                                UIload(Interfacial.PRDTProductOutTextBox);
                                                GetConfigInfos(product, process);
                                                Logger.Print(RuntimeLog.LogType.Debug, "cloud db config excute success");
                                            },
                                            async () =>
                                            {
                                                await SaveAttribute();
                                            });
                                        }
                                        
                                    }
                                    
                                else if (DBTYPE == DB.DB_TYPE.DB_Local)
                                    {
                                        SqliteExceuteResult? result = null;

                                        bool CanInsert = false;

                                        string queryConfigSql = $"SELECT * FROM product_config_field WHERE field_product='{product}' and field_process='{process}'";
                                        if (await DBServer.LocalDBQueryFree(queryConfigSql) is var queryResult)
                                        {
                                            if (queryResult.ErrorHint == null &&
                                                queryResult.Result.TryGetValue(queryConfigSql, out Dictionary<string, ICollection<object>>? ConfigDict))
                                            {
                                                if (ConfigDict is not null &&
                                                    ConfigDict.TryGetValue("field_json", out ICollection<object>? fieldJson))
                                                {
                                                    if (fieldJson.Count == 0)
                                                    {
                                                        CanInsert = true;
                                                    }
                                                    if (fieldJson.Count == 1)
                                                    {
                                                        string insertCommandSql = $"UPDATE product_config_field SET field_json='{_Json}' WHERE " +
                                                                                  $"field_product='{product}' AND " +
                                                                                  $"field_process='{process}'";
                                                        result = await DBServer.LocalDBQueryFree(insertCommandSql);
                                                        Logger.Print(RuntimeLog.LogType.Warning, "local db config update");
                                                    }
                                                }
                                                else CanInsert = true;
                                            }
                                            else CanInsert = true;
                                        }
                                        if (CanInsert)
                                        {
                                            string insertCommandSql = $"INSERT INTO product_config_field VALUES(" +
                                                                      $"'{_Json}'," +
                                                                      $"'{product}'," +
                                                                      $"'{process}')";
                                            result = await DBServer.LocalDBQueryFree(insertCommandSql);
                                            Logger.Print(RuntimeLog.LogType.Warning, "local db config import");
                                        }
                                        if (result is not null && result.ChangeRow is not null and long _count && _count > 0)
                                        {
                                            GetConfigInfos(product, process);
                                            UIload(Interfacial.PRDTProductOutTextBox);
                                        }
                                        
                                    }
                            }
                        })
                        {
                            IsBackground = true
                        };
                        Thread.Start();
                    }
                }
                catch (Exception error)
                {
                    Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
                }
            });
        }

        //  将Mes数据对应关系存入本地
        private async void CaptrueMesrelation(object? param)
        {
            if (param is not null and ICollection<KvpGroup> _MesMap)
            {
                string jsonconfig = System.Text.Json.JsonSerializer.Serialize(_MesMap, Function.SafetyReferenceJsonOptions);

                await IOServer.WriteAsync(LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.MesMap), jsonconfig);

                LoadLocalMesConfigMap();
            }
            else
            {
                VarbinVsstMesMap = false;
            }
        }

        //  初始化任务
        public async void ReadyWork()
        {
            try
            {
                //  加载顶部菜单
                TopMenuOptionsLoad();

                var watch = Stopwatch.StartNew();
                DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));

                if (DBTYPE == DB.DB_TYPE.DB_Cloud)
                {
                    if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                    {
                        GetProductInfos();
                    }

                }
                else if (DBTYPE == DB.DB_TYPE.DB_Local)
                {
                    var parallelOptions = new ParallelOptions
                    {
                        MaxDegreeOfParallelism = 3
                    };

                    await TableCreate();

                    GetProductInfos();


                }
                else if (DBTYPE == DB.DB_TYPE.DB_Null)
                {
                    ReadyWork();
                }
                    
                LoadCondigOptions();

                Logger.Print(RuntimeLog.LogType.Debug, $"{MethodBase.GetCurrentMethod()?.Name} running");
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }

            LogSweep(); //  日志清理
        }

        //  表创建
        private async Task TableCreate()
        {
            await Task.Run(async () =>
            {
                try
                {
                    string verityTableSql = "select name from sqlite_master where type='table'";

                    var sqltablecreate = await DBServer.LocalDBQueryFree(verityTableSql);

                    List<string> unexistsTables = [];

                    foreach (var key in HoldActivitySectionModel.TableReserveDuty.Keys)
                    {
                        if (sqltablecreate.ErrorHint == null && sqltablecreate.Result.TryGetValue(verityTableSql, out var keyValues))
                        {
                            if (keyValues.TryGetValue("name", out ICollection<object>? tables) && tables is not null)
                            {
                                if (!tables.Contains(key)) unexistsTables.Add(HoldActivitySectionModel.TableReserveDuty[key]);
                            }
                            else
                            {
                                unexistsTables.Add(HoldActivitySectionModel.TableReserveDuty[key]);
                            }
                        }
                        else
                        {
                            unexistsTables.Add(HoldActivitySectionModel.TableReserveDuty[key]);
                        }
                    }
                    if (await DBServer.LocalDBQuery(unexistsTables) is SqliteExceuteResult result &&
                        result.ErrorHint == null)
                    {
                        Logger.Debug("dispose sql of table create");
                    }
                    else
                    {
                        Logger.Error("table create fail");
                    }
                }
                catch (Exception error)
                {
                    Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
                }
            }).ConfigureAwait(false);
        }

        //  获取串口输出
        public void SerialDataReceive(string receive)
        {
            ActivityDetetor.Run(receive);
            LogRecord(receive, true);
        }

        //  测试内容处理
        private void ReturnReceipt(FlyingDove Message)
        {
            MessageProPlantType Type = Message.Type;
            int index = Message.Row;
            object? message = Message.Message;
            bool isQuestion = Message.AssertQuestion;

            Application.Current.Dispatcher.Invoke(async () =>
            {
                try
                {
                    if (Type.HasFlag(MessageProPlantType.Success))
                    {
                        if (ActivityExpoListItems.Count > index)
                        {
                            ActivityExpoListItems[index] = new TestItemSurfaceSealed(ActivityExpoListItems[index].ActivityName, "JadeFlow".FindSolidBrush());
                        }
                    }

                    if (Type.HasFlag(MessageProPlantType.Failed))
                    {
                        if (ActivityExpoListItems.Count > index)
                        {
                            ActivityExpoListItems[index] = new TestItemSurfaceSealed(ActivityExpoListItems[index].ActivityName, "SunsetCoral".FindSolidBrush());
                            if (!string.IsNullOrEmpty(HoldActivitySectionModel.ProductSelectedValuePair.Item1) && 
                                !string.IsNullOrEmpty(HoldActivitySectionModel.ProductSelectedValuePair.Item2))
                            {
                                await CustomMessageBox.Show(
                                    new CustomMessageBox.InquiryDlPopupSetting
                                    {
                                        Msg_Title = $"{HoldActivitySectionModel.ProductSelectedValuePair.Item1} - {HoldActivitySectionModel.ProductSelectedValuePair.Item1}",
                                        Msg_BodyText = $"{HoldActivitySectionModel.ProductSelectedValuePair.Item2}测试不通过",
                                        Msg_Result = 0,
                                        Msg_DelayExitTime = 2600
                                    });
                            }
                        }
                    }

                    if (Type.HasFlag(MessageProPlantType.Question))
                    {
                        if (message is not null && message is CustomMessageBox.InquiryPopupField FieldMessage)
                        {
                            if (FieldMessage.itemsSource.Count > 0)
                            {
                                CustomMessageBox.InquiryPopupInvoke Invoke = CustomMessageBox.Show(
                                    new CustomMessageBox.InquiryListPopupSetting
                                    {
                                        Msg_Title = FieldMessage.title,
                                        Msg_InquiryButtoms = FieldMessage.options,
                                        Msg_ItemsSource = FieldMessage.itemsSource,
                                    });
                                ActivityDetetor.SendQuestioning(Invoke);
                            }
                            else
                            {
                                CustomMessageBox.InquiryPopupInvoke Invoke = await CustomMessageBox.Show(
                                    new CustomMessageBox.InquiryNmPopupSetting
                                    {
                                        Msg_Title = FieldMessage.title,
                                        Msg_InquiryIcon = FieldMessage.type,
                                        Msg_InquiryButtoms = FieldMessage.options,
                                        Msg_BodyText = FieldMessage.message,
                                        Msg_WinWidth = 480,
                                        Msg_WinHeight = 270
                                    });
                                ActivityDetetor.SendQuestioning(Invoke);
                            }
                        }
                    }

                    if (Type.HasFlag(MessageProPlantType.Message))
                    {
                        if (message is not null and string _message)
                        {
                            DynamicRichContent.Add(new EnjoyRichTextBox.Text
                            {
                                Contnet = _message + "\n\n"
                            });
                            LogRecord(_message, false);
                        }
                        else if (message is not null and EnjoyRichTextBox.Text _text)
                        {
                            _text.Contnet += "\n\n";
                            DynamicRichContent.Add(_text);
                            LogRecord(_text.Contnet, false);
                        }
                    }

                    if (Type.HasFlag(MessageProPlantType.PushFinish))
                    {
                        await CustomMessageBox.Show(
                            new CustomMessageBox.InquiryDlPopupSetting
                            {
                                Msg_Title = $"{HoldActivitySectionModel.ProductSelectedValuePair.Item1} - {HoldActivitySectionModel.ProductSelectedValuePair.Item2}",
                                Msg_BodyText = $"{HoldActivitySectionModel.ProductSelectedValuePair.Item2}测试通过",
                                Msg_Result = 2,
                                Msg_DelayExitTime = 2500,
                                Msg_CloseCallback = () =>
                                {
                                    if (HoldActivitySectionModel.TestDemandType == DemandType.Mes)
                                    {
                                        if (HoldActivitySectionModel.MesConfigMap.TryGetValue(ActivityDetetor.Actvt_PapPair.Item2, out KvpGroup _struct))
                                        {
                                            if (message is not null)
                                            {
                                                MesHttpSend(_struct, message);
                                            }
                                        }

                                        else
                                        {
                                            DynamicRichContent.Add(new EnjoyRichTextBox.Text
                                            {
                                                Contnet = "当前Mes配置未匹配到当前工序，如当前工序需要发送Mes消息，请点击此处进行配置,如不需要上报Mes，则忽略该消息\r\n\r\n",
                                                TxType = EnjoyRichTextBox.TextType.HyperLink,
                                                Foreground = "TwilightZone",
                                                FontWeight = FontWeights.ExtraBold,
                                                BindingData = new HyperlinkBack
                                                {
                                                    LinkType = HyperlinkBackType.MesDataBindingFace,
                                                }
                                            });

                                            DynamicRichContent.Add(new EnjoyRichTextBox.Text
                                            {
                                                Contnet = "完成配置后可点击此文本重发Mes消息\r\n\r\n",
                                                TxType = EnjoyRichTextBox.TextType.HyperLink,
                                                Foreground = "TwilightZone",
                                                FontWeight = FontWeights.ExtraBold,
                                                BindingData = new HyperlinkBack
                                                {
                                                    LinkType = HyperlinkBackType.MesHttpRequest,
                                                    BindingData = new List<object>() { _struct, message ?? string.Empty }
                                                }
                                            });
                                        }
                                    }
                                    FocusAndClearing();
                                },
                                Msg_WinRadius = 6
                            });
                    }

                    if (Type.HasFlag(MessageProPlantType.HeartBeats))
                    {
                        if (message is not null)
                        {
                            VarbinTestButtomText = message.GetSafetyChar();
                        }
                    }

                    if (Type.HasFlag(MessageProPlantType.Initialize))
                    {
                        await RecoverEctivityListItem();
                    }

                    if (Type.HasFlag(MessageProPlantType.DimProcess))
                    {
                        if (message is not null and KeyValuePair<double, string> _process)
                        {
                            if (HoldActivitySectionModel.DimProcess is null) HoldActivitySectionModel.DimProcess = await CustomMessageBox.Show(
                                new CustomMessageBox.ShowyPrograssSetting
                                {
                                    Msg_Minnum = 0,
                                    Msg_Maxnum = 10,
                                    Msg_DelayExitTime = 300
                                });

                            if (_process.Key == 10.0)
                            {
                                HoldActivitySectionModel.DimProcess.Invoke(_process.Key, _process.Value);
                                HoldActivitySectionModel.DimProcess = null;
                            }
                            else
                            {
                                HoldActivitySectionModel.DimProcess.Invoke(_process.Key, _process.Value);
                            }
                        }
                    }

                    if (Type.HasFlag(MessageProPlantType.ResultRegister))
                    {
                        if (message is not null and TestResultRegister _result)
                        {
                            await TestResultPutStorage(_result);
                            LogRecord(string.Empty, true, true);
                            LogRecord(string.Empty, false, true);
                        }
                    }

                }
                catch (Exception error)
                {
                    Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
                }
            });
        }

        //  记录测试日志
        private async void LogRecord(string content, bool isDevice = true, bool BeginWrite = false)
        {
            if (ActivityDetetor.State())
            {
                if (isDevice)
                {
                    HoldActivitySectionModel.Device_TestRunningRecor.Append(content.WrapWord());
                }
                else
                {
                    HoldActivitySectionModel.Tools_TestRunningRecor.Append(content.WrapWord());
                }
            }
            if (BeginWrite)
            {
                if (isDevice)
                {
                    string _RecordContent = HoldActivitySectionModel.Device_TestRunningRecor.ToString();

                    if (_RecordContent.Length > 0) 
                    {
                        string Dvlpath = LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.DVLog, null, "log");
                        if (IOServer.CreateFile(Dvlpath) is not null and string _Dvlpath)
                        {
                            await IOServer.WriteAsync(_Dvlpath, _RecordContent);

                            HoldActivitySectionModel.Device_TestRunningRecor.Clear();
                            HoldActivitySectionModel.Device_TestRunningRecor.Capacity = 4096;
                        } 
                    }
                }
                else
                {
                    string _RecordContent = HoldActivitySectionModel.Tools_TestRunningRecor.ToString();

                    if (_RecordContent.Length > 0)
                    {
                        string Norpath = LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.TSTLog, null, "log");

                        if (IOServer.CreateFile(Norpath) is not null and string _Norpath)
                        {
                            await IOServer.WriteAsync(_Norpath, _RecordContent);

                            HoldActivitySectionModel.Tools_TestRunningRecor.Clear();
                            HoldActivitySectionModel.Tools_TestRunningRecor.Capacity = 4096;
                        }
                    }
                }
            }
        }

        //  定期清理本地日志，周期为 1 个月
        private void LogSweep()
        {
            IOServer.GetLocalFilesAsync(new LocalFileFilterOptions
            (
                Path.Combine("MyApp".CurrentDir(), "TestRunningLog"),
                string.Empty,
                "log",
                async (file) =>
                {
                    string SlippyName = IOServer.GetSlippyName(file.Item1);

                    string date = RegExp.RegExpDateMatch().Match(SlippyName).Value;

                    if (!string.IsNullOrEmpty(date))
                    {
                        if (DateTime.TryParseExact(date, date.ConvertDateFormat(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime _Time))
                        {
                            if (DateTime.Now.Month - _Time.Month >= 1)
                            {
                                File.Delete(file.Item1);

                                await Task.Delay(500);
                            }
                        }
                    }
                },
                LocalFileFilterOptions.Mode.Exact
            ));
        }

        //  产品预览信息删除
        private async void ProductViewDeleteEvent(object? param)
        {
            await ProductExtendSample();

            Thread _Load = new(async () =>
            {
                async Task DeleteSuccess()
                {
                    SelectionTree.TreeHint = "数据删除成功";

                    //  更新输入框缓存，清空
                    SelectionTree.Clear();

                    GetProductInfos(() =>
                    {
                        ReworkProductTreeData(() => { });
                    });

                    await Task.Delay(1100);
                    
                    SelectionTree.TreeHint = null;
                    propertyChangeSend(nameof(SelectionTree));
                    
                }

                if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Cloud)
                {
                    if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                    {
                        string json = string.Empty;
                        if (string.IsNullOrEmpty(SelectionTree.TreeStep))
                        {
                            //  以关系表为准，配置表可能没有工序数据，但是关系表肯定存在数据
                            _ = DBServer.CloudAnchorChannel<ProductConfigRelation>(() =>
                            {
                                DeleteSuccess();
                            },
                            async () =>
                            {
                                Supabase.Interfaces.ISupabaseTable<ProductConfigField, Supabase.Realtime.RealtimeChannel>? DeleteConfig =
                                CloudDB.From<ProductConfigField>();

                                if (!string.IsNullOrEmpty(SelectionTree.TreeProduct)) DeleteConfig
                                    .Where(x => x.FieldProduct == SelectionTree.TreeProduct);

                                if (!string.IsNullOrEmpty(SelectionTree.TreeProduct)) DeleteConfig
                                    .Where(x => x.FieldProcess == SelectionTree.TreeProcess);

                                await DeleteConfig.Delete();


                                Supabase.Interfaces.ISupabaseTable<ProductConfigRelation, Supabase.Realtime.RealtimeChannel>? DeleteRelation =
                                CloudDB.From<ProductConfigRelation>();

                                if (!string.IsNullOrEmpty(SelectionTree.TreeProduct)) DeleteRelation
                                    .Where(x => x.PrdName == SelectionTree.TreeProduct);

                                if (!string.IsNullOrEmpty(SelectionTree.TreeProcess)) DeleteRelation
                                    .Where(x => x.PrdProcess == SelectionTree.TreeProcess);

                                await DeleteRelation.Delete();

                            }, null, "DELETE");
                        }
                        else
                        {
                            var queryResult = await CloudDB.From<ProductConfigField>()
                            .Where(x => x.FieldProduct == SelectionTree.TreeProduct && x.FieldProcess == SelectionTree.TreeProcess)
                              .Select(x => new object[] { x.FieldJson })
                              .Get();

                            if (queryResult.Model is not null)
                            {
                                json = queryResult.Model.FieldJson;
                                List<TestItemDeepSeatedSealed>? DejsonCollection = System.Text.Json.JsonSerializer.Deserialize<List<TestItemDeepSeatedSealed>>(
                                                                json, Function.SafetyReferenceJsonOptions);
                                if (DejsonCollection is not null && DejsonCollection.Count > 0)
                                {
                                    if (DejsonCollection.Select(x => x.Step).Contains(SelectionTree.TreeStep))
                                    {
                                        DejsonCollection = [.. DejsonCollection.Where(x => x.Step != SelectionTree.TreeStep)];

                                        string newJson = System.Text.Json.JsonSerializer.Serialize(DejsonCollection);

                                        await DBServer.CloudAnchorChannel<ProductConfigField>(() =>
                                        {
                                            DeleteSuccess();
                                        },
                                        async () =>
                                        {
                                            await CloudDB.From<ProductConfigField>()
                                            .Where(x => x.FieldProduct == SelectionTree.TreeProduct && x.FieldProcess == SelectionTree.TreeProcess)
                                            .Set(x => x.FieldJson, newJson)
                                            .Update();
                                        }, null, "UPDATE");
                                    }
                                    else
                                    {
                                        await CustomMessageBox.Show(new CustomMessageBox.InquiryNmPopupSetting { Msg_Title = "数据库查询异常", Msg_BodyText = "当前步骤不在数据库中", Msg_InquiryButtoms = ["知道了"] });
                                    }
                                }
                            }
                            else
                            {
                                await CustomMessageBox.Show(new CustomMessageBox.InquiryNmPopupSetting { Msg_Title = "数据库查询异常", Msg_BodyText = "产品名称或产品工序异常", Msg_InquiryButtoms = ["知道了"] });
                            }
                        }
                    }
                }

                else if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Local)
                {
                    if (string.IsNullOrEmpty(SelectionTree.TreeStep))
                    {
                        string deleteConfigSql = "DELETE FROM product_config_field WHERE ";

                        string deleteRelationSql = "DELETE FROM product_config_relation WHERE ";

                        List<string> conditions_config = [];
                        List<string> conditions_relation = [];

                        if (!string.IsNullOrEmpty(SelectionTree.TreeProduct))
                        {
                            conditions_config.Add($"field_product='{SelectionTree.TreeProduct}'");
                            conditions_relation.Add($"prd_name='{SelectionTree.TreeProduct}'");
                        }

                        if (!string.IsNullOrEmpty(SelectionTree.TreeProcess))
                        {
                            conditions_config.Add($"field_process='{SelectionTree.TreeProcess}'");
                            conditions_relation.Add($"prd_process='{SelectionTree.TreeProcess}'");
                        }
                        deleteConfigSql += conditions_config.Join(" and ");
                        deleteRelationSql += conditions_relation.Join(" and ");

                        if ((await DBServer.LocalDBQueryFree(deleteConfigSql)).ChangeRow is not null and long _count1 && _count1 >= 0 &&
                            (await DBServer.LocalDBQueryFree(deleteRelationSql)).ChangeRow is not null and long _count2 && _count2 > 0)
                        {
                            await DeleteSuccess();
                        }
                    }
                    else
                    {
                        string queryConfigSql = $"SELECT * FROM product_config_field WHERE field_product='{SelectionTree.TreeProduct}' and field_process='{SelectionTree.TreeProcess}'";

                        SqliteExceuteResult queryResult = await DBServer.LocalDBQueryFree(queryConfigSql);

                        if (queryResult.ErrorHint == null &&
                            queryResult.Result.TryGetValue(queryConfigSql, out Dictionary<string, ICollection<object>>? ConfigDict))
                        {
                            if (ConfigDict is not null &&
                                ConfigDict.Count > 0 &&
                                ConfigDict.TryGetValue("field_json", out ICollection<object>? fieldJson))
                            {
                                if (fieldJson.Count == 1)
                                {
                                    List<TestItemDeepSeatedSealed>? DejsonCollection = JsonSerializer.Deserialize<List<TestItemDeepSeatedSealed>>(
                                                                    fieldJson.ElementAt(0).GetSafetyChar(), Function.SafetyReferenceJsonOptions);

                                    if (DejsonCollection is not null && DejsonCollection.Select(x => x.Step).Contains(SelectionTree.TreeStep))
                                    {
                                        DejsonCollection = [.. DejsonCollection.Where(x => x.Step != SelectionTree.TreeStep)];

                                        string newJson = JsonSerializer.Serialize(DejsonCollection, Function.SafetyReferenceJsonOptions);

                                        string updateConfigSql = $"UPDATE product_config_field SET field_json='{newJson}' WHERE field_product='{SelectionTree.TreeProduct}' and field_process='{SelectionTree.TreeProcess}'";

                                        SqliteExceuteResult updateResult = await DBServer.LocalDBQueryFree(updateConfigSql);

                                        if (updateResult.ChangeRow > 0)
                                        {
                                            DeleteSuccess();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
            
            _Load.Start();
        }

        //  产品预览信息更新
        private async void ProductViewUpdateEvent(object? param)
        {
            await ProductExtendSample();

            Logger.Print(RuntimeLog.LogType.Error, SelectionTree.TreeProduct, SelectionTree.TreeProcess, SelectionTreeStdin.TreeProduct, SelectionTreeStdin.TreeProcess);

            void UpdateSuccess()
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    SelectionTree.TreeHint = "数据更新成功";

                    GetProductInfos(async () =>
                    {
                        ReworkProductTreeData(() => { });

                        //  更新输入框缓存，清空
                        SelectionTree.Clear();
                        await Task.Delay(1100);
                        SelectionTree.TreeHint = null;
                        propertyChangeSend(nameof(SelectionTree));
                    });
                });
            }

            if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Cloud)
            {
                if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                {
                    string json = string.Empty;
                    if (string.IsNullOrEmpty(SelectionTree.TreeStep))
                    {
                        //  以关系表为准，配置表可能没有工序数据，但是关系表肯定存在数据
                        _ = DBServer.CloudAnchorChannel<ProductConfigRelation>(
                        () =>
                        {
                            Logger.Print(RuntimeLog.LogType.Debug, "product relation update success， update config code now");

                            // 更新code
                            string code = CryptServer.ENbase64(SelectionTree.TreeProduct + SelectionTree.TreeProcess);

                            (bool, bool) range = (false, false);

                            Supabase.Interfaces.ISupabaseTable<ProductConfigField, Supabase.Realtime.RealtimeChannel>? UpdateConfig =
                            CloudDB.From<ProductConfigField>();

                            if (!string.IsNullOrEmpty(SelectionTree.TreeProduct))
                            {
                                UpdateConfig
                                .Set(x => x.FieldProduct, SelectionTree.TreeProduct)
                                .Where(x => x.FieldProduct == SelectionTreeStdin.TreeProduct);
                                range.Item1 = true;
                            }

                            if (!string.IsNullOrEmpty(SelectionTree.TreeProcess))
                            {
                                UpdateConfig
                                .Set(x => x.FieldProcess, SelectionTree.TreeProcess)
                                .Where(x => x.FieldProcess == SelectionTreeStdin.TreeProcess);
                                range.Item2 = true;
                            }

                            _ = DBServer.CloudAnchorChannel<ProductConfigField>(
                            async () =>
                            {
                                Logger.Print(RuntimeLog.LogType.Debug, "config prd - pro update success");
                                if (range.Item1 && range.Item2)
                                {
                                    _ = DBServer.CloudAnchorChannel<ProductConfigField>(
                                    () =>
                                    {
                                        UpdateSuccess();
                                        Logger.Print(RuntimeLog.LogType.Debug, $"config code {code} update success");
                                    },
                                    async () =>
                                    {
                                        await CloudDB.From<ProductConfigField>()
                                            .Set(x => x.Code, code)
                                            .Where(x => x.FieldProduct == SelectionTreeStdin.TreeProduct && x.FieldProcess == SelectionTree.TreeProcess)
                                            .Update();
                                        Logger.Print(RuntimeLog.LogType.Debug, "config code update start of contain process");
                                    },
                                    () =>
                                    {
                                        Logger.Print(RuntimeLog.LogType.Debug, "config code update fail");
                                    }, "UPDATE");
                                }
                                else if (range.Item1 && !range.Item2)
                                {
                                    var CodeResult = await CloudDB.From<ProductConfigField>()
                                        .Select(x => new object[] { x.Code })
                                        .Where(x => x.FieldProduct == SelectionTreeStdin.TreeProduct)
                                        .Get();

                                    foreach (var model in CodeResult.Models)
                                    {
                                        string FieldProcess = CryptServer.DEbase64(model.Code).Replace(model.FieldProduct, "");

                                        string newCode = CryptServer.DEbase64(SelectionTree.TreeProduct + FieldProcess);

                                        _ = DBServer.CloudAnchorChannel<ProductConfigField>(
                                        () =>
                                        {
                                            UpdateSuccess();
                                            Logger.Print(RuntimeLog.LogType.Debug, $"old code {model.Code} new code {newCode} update success");
                                        },
                                        async () =>
                                        {
                                            await CloudDB.From<ProductConfigField>()
                                                         .Set(x => x.Code, newCode)
                                                         .Where(x => x.Code == model.Code)
                                                         .Update();
                                            Logger.Print(RuntimeLog.LogType.Fatal, "config code update start of uncontain process");
                                        },
                                        () =>
                                        {
                                            Logger.Print(RuntimeLog.LogType.Fatal, "config code update fail");

                                        }, "UPDATE");

                                        await Task.Delay(1000);
                                    }
                                }
                            },
                            async () =>
                            {
                                await UpdateConfig.Update();
                                Logger.Print(RuntimeLog.LogType.Debug, "product config update start");
                            }, null, "UPDATE");
                        },
                        async () =>
                        {
                            Supabase.Interfaces.ISupabaseTable<ProductConfigRelation, Supabase.Realtime.RealtimeChannel>? UpdateRelation =
                            CloudDB.From<ProductConfigRelation>();

                            if (!string.IsNullOrEmpty(SelectionTree.TreeProduct))
                            {
                                UpdateRelation
                                .Set(x => x.PrdName, SelectionTree.TreeProduct)
                                .Where(x => x.PrdName == SelectionTreeStdin.TreeProduct);
                            }

                            if (!string.IsNullOrEmpty(SelectionTree.TreeProcess))
                            {
                                UpdateRelation
                                .Set(x => x.PrdProcess, SelectionTree.TreeProcess)
                                .Where(x => x.PrdProcess == SelectionTreeStdin.TreeProcess);
                            }

                            if (!string.IsNullOrEmpty(SelectionTree.TreeProduct) &&
                                !string.IsNullOrEmpty(SelectionTree.TreeProcess) &&
                                SelectionTree.TreeProduct != SelectionTreeStdin.TreeProduct &&
                                !LeisureProducts.Contains(SelectionTree.TreeProduct))
                            {
                                RegisterExcuteSave(SelectionTree.TreeProduct, string.Empty, 0, true);
                            }

                            await UpdateRelation.Update();

                            Logger.Print(RuntimeLog.LogType.Fatal, "start product relation update");
                        },
                        () =>
                        {
                            Logger.Print(RuntimeLog.LogType.Fatal, "product relation update fail");

                        }, "UPDATE");
                    }
                }
            }
                
            else if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Local)
            {
                (string, string) GetSqlSection(EmbeddedTreeStructureSelect _Select, string _s = ",")
                {
                    List<string> config = [];
                    List<string> relation = [];

                    if (!string.IsNullOrEmpty(_Select.TreeProduct))
                    {
                        config.Add($"field_product='{_Select.TreeProduct}'");
                        relation.Add($"prd_name='{_Select.TreeProduct}'");
                    }

                    if (!string.IsNullOrEmpty(_Select.TreeProcess))
                    {
                        config.Add($"field_process='{_Select.TreeProcess}'");
                        relation.Add($"prd_process='{_Select.TreeProcess}'");

                    }
                    return (config.Join(_s), relation.Join(_s));
                }

                string updateConfigSql = "UPDATE product_config_field SET ";

                string updateRelationSql = "UPDATE product_config_relation SET ";

                if (!string.IsNullOrEmpty(SelectionTree.TreeProduct) &&
                    !string.IsNullOrEmpty(SelectionTree.TreeProcess) &&
                    SelectionTree.TreeProduct != SelectionTreeStdin.TreeProduct &&
                    !LeisureProducts.Contains(SelectionTree.TreeProduct))
                {
                    RegisterExcuteSave(SelectionTree.TreeProduct, string.Empty, 0, true);
                }

                var SetInfo = GetSqlSection(SelectionTree);
                var Condition = GetSqlSection(SelectionTreeStdin, " and ");

                updateConfigSql += SetInfo.Item1 + " WHERE " + Condition.Item1;
                updateRelationSql += SetInfo.Item2 + " WHERE " + Condition.Item2;

                if ((await DBServer.LocalDBQueryFree(updateConfigSql)).ChangeRow is not null and long _count1 && _count1 >= 0 &&
                    (await DBServer.LocalDBQueryFree(updateRelationSql)).ChangeRow is not null and long _count2 && _count2 > 0)
                {
                    UpdateSuccess();
                }
            }
        }

        //  产品预览展开情况留底
        private async Task<bool> ProductExtendSample(string? parent = null, string? treename = null)
        {
            bool isExtend = false;

            await Task.Run(() =>
            {
                if (parent is null && treename is null)
                {
                    HoldActivitySectionModel.EmbeddedIsExtend.Clear();

                    foreach (var _struct in HoldEmbeddedTreeStructures)
                    {
                        HoldActivitySectionModel.EmbeddedIsExtend.Add((_struct.TreeParent, _struct.TreeName, _struct.IsExpand));
                    }
                }
                else
                {
                    foreach (var _combination in HoldActivitySectionModel.EmbeddedIsExtend)
                    {
                        if (!parent.IsNullOrEmpty())
                        {
                            if (_combination.Item1 == parent && _combination.Item2 == treename)
                            {
                                isExtend = _combination.Item3;
                            }
                        }
                        else if (parent.IsNullOrEmpty())
                        {
                            if (_combination.Item2 == treename)
                            {
                                isExtend = _combination.Item3;
                            }
                        }
                    }
                }
            }).ConfigureAwait(false);

            return isExtend;
        }

        //  二次加载树状图数据,此为树状图组件打开主方法
        private void ReworkProductTreeData(Action ReworkCallBack)
        {
            Thread _Load = new(async () =>
            {
                void Add(string product, string process, string json)
                {
                    foreach (var tree in HoldEmbeddedTreeStructures)
                    {
                        if (tree.TreeName == product)
                        {
                            List<EmbeddedTreeStructure> _ChildTree = [.. tree.ProductRelationChildTree];
                            foreach (var childTree in _ChildTree)
                            {
                                if (childTree.TreeName == process)
                                {
                                    List<TestItemDeepSeatedSealed>? DejsonCollection = System.Text.Json.JsonSerializer.Deserialize<List<TestItemDeepSeatedSealed>>(
                                                                    json, Function.SafetyReferenceJsonOptions);
                                    if (DejsonCollection is not null)
                                    {
                                        List<EmbeddedTreeStructure> processTree = [.. DejsonCollection.OrderBy(x => x.Priority)
                                        .Select(x => new EmbeddedTreeStructure
                                        {
                                            TreeIcon = EmbeddedTreeStructure.Icon(false),
                                            TreeName = x.Step,
                                            IsChild = true,
                                            TreeCount = 0,
                                            TreeParent = tree.TreeName + "+" + childTree.TreeName,
                                        })];
                                        childTree.TreeCount = processTree.Count;
                                        childTree.ProductRelationChildTree = processTree;
                                    }
                                }
                            }
                        }
                    }
                }

                bool isValid = false;
                if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Cloud)
                {
                    if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                    {
                        var queryResult = await CloudDB.From<ProductConfigField>()
                            .Select(x => new object[] { x.FieldProduct, x.FieldProcess, x.FieldJson })
                            .Get();

                        if (queryResult.Models.Count > 0)
                        {
                            foreach (var model in queryResult.Models)
                            {
                                Add(model.FieldProduct, model.FieldProcess, model.FieldJson);
                            }
                            ReworkCallBack.Invoke();
                            isValid = true;
                        }
                    }
                }
                else if (DBServer.GetDBIdentify() == DB.DB_TYPE.DB_Local)
                {

                    string queryConfigSql = $"SELECT * FROM product_config_field";

                    SqliteExceuteResult queryResult = await DBServer.LocalDBQueryFree(queryConfigSql);

                    if (queryResult.ErrorHint == null &&
                        queryResult.Result.TryGetValue(queryConfigSql, out Dictionary<string, ICollection<object>>? ConfigDict))
                    {
                        if (ConfigDict.TryGetValue("field_json", out ICollection<object>? field_jsons) &&
                            ConfigDict.TryGetValue("field_product", out ICollection<object>? field_products) &&
                            ConfigDict.TryGetValue("field_process", out ICollection<object>? field_processs))
                        {
                            for (int index = 0; index < field_products.Count; index++)
                            {
                                Add(field_products.ElementAt(index).GetSafetyChar(),
                                    field_processs.ElementAt(index).GetSafetyChar(),
                                    field_jsons.ElementAt(index).GetSafetyChar());
                            }
                            ReworkCallBack.Invoke();
                            isValid = true;
                        }
                    }
                }
                if (!isValid) ReworkCallBack.Invoke();
            });
            _Load.Start();
        }

        //  退出产品预览界面
        private void ProductViewExitEvent(object? param)
        {
            UIload(Interfacial.PRDTProductOutTextBox);
        }

        //  测试结果推送
        private async Task TestResultPutStorage(TestResultRegister Result)
        {
            try
            {
                DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));
                
                if (string.IsNullOrEmpty(Result.Imei)) Result.Imei = HoldMesargGroups.Barcodes; //  不存在IMEI时，且正好有MES数据时使用PCD条码替代

                if (DBTYPE == DB.DB_TYPE.DB_Cloud)
                {
                    if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                    {
                        await DBServer.CloudAnchorChannel<TestResultRegister>(() =>
                        {
                            Logger.Print(RuntimeLog.LogType.Warning, "test result rescord success");
                        },
                        async () =>
                        {
                            await CloudDB.From<TestResultRegister>()
                                            .Insert(Result);
                        });

                        if (HoldActivitySectionModel.ProductStalkerMap.TryGetValue(HoldActivitySectionModel.CurrentProductFlag, out List<Template>? _Templates) &&
                            _Templates.Count > 0)
                        {
                            var Query = await CloudDB.From<TestResultRegisterElite>()
                                .Where(x=>x.Product == Result.Product)
                                .Get();

                            CommandWatchHint(Query.Models.OrderByDescending(x=>x.Date.ConvertDateFormat(6).Item2), _Templates);
                        }
                    }
                }

                else if (DBTYPE == DB.DB_TYPE.DB_Local)
                    {
                        int _result = Result.Result ? 1 : 0;
                        string insertSql = $@"INSERT INTO testresult_register (
                                            product, process, step, imei, origin, result, subjoin, date) VALUES (
                                            '{Result.Product}',
                                            '{Result.Process}', 
                                            '{Result.Step}', 
                                            '{Result.Imei}',
                                            '{Result.Origin}',
                                             {_result},
                                            '{Result.Subjoin}',
                                            '{Result.Date}')";
                        SqliteExceuteResult? result = await DBServer.LocalDBQueryFree(insertSql);

                        if (string.IsNullOrEmpty(result.ErrorHint))
                        {
                            Logger.Print(RuntimeLog.LogType.Warning, "test result rescord success");
                        }

                        if (HoldActivitySectionModel.ProductStalkerMap.TryGetValue(HoldActivitySectionModel.CurrentProductFlag, out List<Template>? _Templates) &&
                            _Templates.Count > 0)
                        {

                            List<TestResultRegisterElite> ValidDatas = [];

                            string querySql = $@"SELECT * FROM testresult_register WHERE product='{Result.Product}';";
                            SqliteExceuteResult? queryResult = await DBServer.LocalDBQueryFree(querySql);

                            if (queryResult.ErrorHint == null &&
                                queryResult.Result.TryGetValue(querySql, out Dictionary<string, ICollection<object>>? dataDict) &&
                                dataDict.TryGetValue("id", out ICollection<object>? Ids) &&
                                dataDict.TryGetValue("product", out ICollection<object>? Products) &&
                                dataDict.TryGetValue("process", out ICollection<object>? Processs) &&
                                dataDict.TryGetValue("step", out ICollection<object>? Steps) &&
                                dataDict.TryGetValue("imei", out ICollection<object>? Imeis) &&
                                dataDict.TryGetValue("origin", out ICollection<object>? Origins) &&
                                dataDict.TryGetValue("result", out ICollection<object>? Results) &&
                                dataDict.TryGetValue("subjoin", out ICollection<object>? Subjoins) &&
                                dataDict.TryGetValue("date", out ICollection<object>? Dates))
                            {
                                for (int index = 0; index < Imeis.Count; index++)
                                {
                                    string _IMEI = Imeis.GetSafetyChar(index).GetSafetyChar();
                                    if (!string.IsNullOrEmpty(_IMEI))
                                    {
                                        TestResultRegisterElite testResult = new()
                                        {
                                            Product = Products.GetSafetyChar(index).GetSafetyChar(),
                                            Process = Processs.GetSafetyChar(index).GetSafetyChar(),
                                            Step = Steps.GetSafetyChar(index).GetSafetyChar(),
                                            Imei = _IMEI,
                                            Subjoin = Subjoins.GetSafetyChar(index).GetSafetyChar(),
                                            Origin = Origins.GetSafetyChar(index).GetSafetyChar(),
                                            Date = Dates.GetSafetyChar(index).GetSafetyChar()
                                        };
                                        if (bool.TryParse(Results.GetSafetyChar(index), out bool reslult))
                                        {
                                            testResult.Result = reslult;
                                        }
                                        if (long.TryParse(Ids.GetSafetyChar(index), out long id))
                                        {
                                            testResult.ID = id;
                                        }
                                        ValidDatas.Add(testResult);
                                    }
                                }
                            }
                            CommandWatchHint(ValidDatas.OrderByDescending(x => x.Date.ConvertDateFormat(6).Item2), _Templates);
                        }
                        
                    }

            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Error, $"{MethodBase.GetCurrentMethod()?.Name} Error: {error.Message}");
            }
        }

        //  测试结果分析
        private void CommandWatchHint(IEnumerable<TestResultRegisterElite> TestResults, List<Template> Templates)
        {
            Task.Run(async () =>
            {
                //  步骤 - 观察类型 - 按钮信息对象 - 按钮提示
                //  累计匹配到的数据数 + 设置的允许最大匹配数 + 设置的最大抽样数 + 符合匹配的总数据数(状态、步骤名、时间符合条件就统计)
                Dictionary<(string, string, string, string), (int, int, int, int)> StatisticalMap = [];

                //  数据满足条件数据留底
                Dictionary< (string, string), List<long>> MeetConditionIndexMap = [];
                Dictionary<(string, string),  List<string>> MeetConditionSujoinMap = [];

                void AddsqlPrepare((string, string) keys, long? index, string subjoin)
                {
                    if (index is not null and long _index)
                    {
                        if (MeetConditionIndexMap.TryGetValue(keys, out List<long>? _indexs))
                        {
                            _indexs.Add(_index);
                        }
                        else
                        {
                            MeetConditionIndexMap.Add(keys, [_index]);
                        }

                        if (MeetConditionSujoinMap.TryGetValue(keys, out List<string>? _subjoins))
                        {
                            _subjoins.Add(subjoin);
                        }
                        else
                        {
                            MeetConditionSujoinMap.Add(keys, [subjoin]);
                        }
                    }
                }

                //  entry - 准入  way - 方式， 1是非抽样统计， 2是抽样统计  key - 步骤 - 观察类型 - 按钮信息对象 - 按钮提示
                //  wcc 观察的次数数据，可能是单个int类型，也可能是int+int类型， cck总的计数
                void Assert(bool entry, int way, (string, string, string, string) key, string wcc, int cck, TestResultRegisterElite model)
                {
                    switch (way)
                    {
                        case 1:
                            if (entry)
                            {
                                if (StatisticalMap.ContainsKey(key))
                                {
                                    (int, int, int, int) value = StatisticalMap[key];
                                    StatisticalMap[key] = (++value.Item1, value.Item2, value.Item3, cck);
                                }
                                else
                                {
                                    if (int.TryParse(wcc, out int _WatchCount))
                                    {
                                        StatisticalMap.Add(key, (1, _WatchCount, -1, cck));
                                    }
                                }
                                AddsqlPrepare((key.Item1, key.Item2), model.ID, model.Subjoin);
                            }
                            break;

                        case 2:
                            if (wcc.Contains('+'))
                            {
                                string[] WatchCountSqlit = wcc.Split('+');
                                if (WatchCountSqlit.Length == 2)
                                {
                                    if (int.TryParse(WatchCountSqlit.ElementAt(0), out int _Success) &&
                                        int.TryParse(WatchCountSqlit.ElementAt(1), out int _Total) &&
                                        _Total >= cck && entry)
                                    {
                                        if (StatisticalMap.ContainsKey(key))
                                        {
                                            (int, int, int, int) value = StatisticalMap[key];
                                            AddsqlPrepare((key.Item1, key.Item2), model.ID, model.Subjoin);
                                            StatisticalMap[key] = (++value.Item1, value.Item2, value.Item3, cck);
                                        }
                                        else
                                        {
                                            StatisticalMap.Add(key, (1, _Success, _Total, cck));
                                            AddsqlPrepare((key.Item1, key.Item2), model.ID, model.Subjoin);
                                        }
                                    }
                                }
                            }
                            break;
                    }
                }

                foreach (var Template in Templates)
                {
                    int CanCheckCount = 0;
                    string Step = Template.Step;
                    bool State = Template.State;
                    string Watch = Template.Watch;
                    DateTime ConvertDate = DateTime.Now.AddDays(-Template.Date); // 当前时间
                    string WatchCount = Template.WatchCount;

                    foreach (var model in TestResults)
                    {
                        IEnumerable<string[]> subjoins = RegExp.RegExpAndSpacing().Split(model.Subjoin).Select(x => x.Split(':'));
                        DateTime sqldate = model.Date.ConvertDateFormat(6).Item2;  // 数据库时间

                        foreach (var single in subjoins)
                        {
                            if (single.Length == 2)
                            {
                                string SqlStep = single[0];
                                string SqlValue = single[1];
                                if (State && SqlStep.Equals(Step, StringComparison.CurrentCultureIgnoreCase) && sqldate >= ConvertDate) // 时间比对
                                {
                                    string ButtomFuncSerial = JsonSerializer.Serialize(Template.ButActions, Function.SafetyReferenceJsonOptions);
                                    CanCheckCount++;
                                    switch (Watch)
                                    {
                                        case "成功阈值":
                                            Assert(!string.IsNullOrEmpty(SqlValue.Trim()), 1, (Step, Watch, ButtomFuncSerial, Template.Hint), WatchCount, CanCheckCount, model);
                                            break;

                                        case "失败阈值":
                                            Assert(string.IsNullOrEmpty(SqlValue.Trim()), 1, (Step, Watch, ButtomFuncSerial, Template.Hint), WatchCount, CanCheckCount, model);
                                            break;

                                        case "成功阈值+抽样数量":
                                            Assert(!string.IsNullOrEmpty(SqlValue.Trim()), 2, (Step, Watch, ButtomFuncSerial, Template.Hint), WatchCount, CanCheckCount, model);
                                            break;

                                        case "失败阈值+抽样数量":
                                            Assert(string.IsNullOrEmpty(SqlValue.Trim()), 2, (Step, Watch, ButtomFuncSerial, Template.Hint), WatchCount, CanCheckCount, model);
                                            break;
                                    }
                                }
                            }
                        }
                    }
                }

                foreach (var sec in StatisticalMap)
                {
                    bool state = false;
                    string step = sec.Key.Item1; //  观察的步骤
                    string watch = sec.Key.Item2; //  观察类型
                    string hint = sec.Key.Item4;
                    ObservableCollection<ButtomFunc>? buttoms = System.Text.Json.JsonSerializer.Deserialize<ObservableCollection<ButtomFunc>>(
                        sec.Key.Item3, 
                        Function.SafetyReferenceJsonOptions); //  弹框信息
                    int curcount = sec.Value.Item1; //  满足的计数
                    int ideal_num = sec.Value.Item2; //  预期的计数
                    int ideal_totalnum = sec.Value.Item3; //  预期的计数参考值
                    int allcount = sec.Value.Item4; //  总计数

                    string statement = string.Empty;

                    if (ideal_totalnum == -1)
                    {
                        if (curcount >= ideal_num)
                        {
                            state = true;
                            statement = $"当前计数: {curcount} 大于等于 预期计数: {ideal_num}\r\n";
                        }
                    }
                    else
                    {
                        if (curcount >= ideal_num && allcount >= ideal_totalnum)
                        {
                            state = true;
                            statement = $"当前计数: {curcount} 大于等于 预期计数: {ideal_num}, 总计数: {allcount} 满足 抽样阈值: {ideal_totalnum}\r\n";
                        }
                    }

                    Logger.Print(RuntimeLog.LogType.Info, curcount, ideal_num, ideal_totalnum, allcount, state, buttoms is not null);

                    if (state && buttoms is not null)
                    {
                        CustomMessageBox.InquiryPopupInvoke Question = await CustomMessageBox.Show(
                            new CustomMessageBox.InquiryNmPopupSetting
                            {
                                Msg_Title = $"{step} 观察结果",
                                Msg_InquiryIcon = 1,
                                Msg_InquiryButtoms = [.. buttoms.Select(x => x.BTName)],
                                Msg_BodyText = statement + hint,
                                Msg_WinWidth = 400,
                                Msg_WinHeight = 210
                            });

                        int SelectIndex = Question.index;
                        string action = buttoms[SelectIndex].BTAction;

                        switch (action)
                        {
                            case "取消":

                                break;

                            case "清除记录":
                                if (MeetConditionSujoinMap.TryGetValue((step, watch), out List<string>? _meetsubjoins) &&
                                    MeetConditionIndexMap.TryGetValue((step, watch), out List<long>? _meetindexs))
                                {
                                    List<string> ClearSubjoins = [.._meetsubjoins.Select(x => RegExp.RegExpAndSpacing().Split(x).Where(x => !x.Contains(step)).Join("&&"))];

                                    List<TestResultRegisterElite> MeetConditionModels = [];

                                    foreach (var res in TestResults)
                                    {
                                        if (res.ID is long _index && 
                                            _meetindexs.IndexOf(_index) is int _indexof && 
                                            _indexof != -1 && 
                                            ClearSubjoins.Count > _indexof)
                                        {
                                            res.Subjoin = ClearSubjoins[_indexof];
                                            MeetConditionModels.Add(res);
                                        }
                                    }

                                    DB.DB_TYPE DBTYPE = await DBServer.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));

                                    if (DBTYPE == DB.DB_TYPE.DB_Cloud)
                                    {
                                        if (DBServer.GetCloudDB() is not null and Supabase.Client CloudDB)
                                        {
                                            await DBServer.CloudAnchorChannel<TestResultRegister>(() =>
                                            {
                                                Logger.Print(RuntimeLog.LogType.Warning, "cloud test upsert success");
                                            },
                                            async () =>
                                            {
                                                await CloudDB.From<TestResultRegisterElite>()
                                                .Upsert(MeetConditionModels);
                                            });
                                        }
                                    }

                                    else if (DBTYPE == DB.DB_TYPE.DB_Local)
                                    {
                                        foreach (var Result in MeetConditionModels)
                                        {
                                            int _result = Result.Result ? 1 : 0;
                                            string insertSql = $@"UPDATE testresult_register SET subjoin='{Result.Subjoin}' WHERE id={Result.ID}";
                                            SqliteExceuteResult? result = await DBServer.LocalDBQueryFree(insertSql);

                                            if (string.IsNullOrEmpty(result.ErrorHint))
                                            {
                                                Logger.Print(RuntimeLog.LogType.Warning, "local test upsert success");
                                            }
                                        }
                                    }
                                }
                                break;
                        }
                    }
                }
            });
        }

        //  加载顶部菜单
        private void TopMenuOptionsLoad()
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                HoldTopMenuOptions.Clear();

                HoldTopMenuOptions.Add
                (
                    new TopMenuOptions
                    {
                        Icon = "\ue626",
                        MenuName = "测试结果预览",
                        Command = CmdTopMenuTestStatistical
                    }
                );

                HoldTopMenuOptions.Add
                (
                   new TopMenuOptions
                   {
                       Icon = "\ue946",
                       MenuName = "清空串口输出",
                       Command = CmdClearSerialOut
                   }
                );

                HoldTopMenuOptions.Add
                (
                   new TopMenuOptions
                   {
                       Icon = "\ue64e",
                       MenuName = "Mes数据绑定",
                       Command = CmdMesDataBinding
                   }
                );

                HoldTopMenuOptions.Add
                (
                   new TopMenuOptions
                   {
                       Icon = "\ue66b",
                       MenuName = "Mes/附加配置",
                       Command = CmdAssistConfigOpen
                   }
                );

                HoldTopMenuOptions.Add
                (
                    new TopMenuOptions
                    {
                        Icon = "\ue66b",
                        MenuName = "指令提示配置",
                        Command = CmdStalkerStepShow
                    }
                );

                HoldTopMenuOptions.Add
                (
                    new TopMenuOptions
                    {
                        Icon = "\ue6fc",
                        MenuName = "正则工具",
                        Command = CmdRegexpTestTool
                    }
                );

                HoldTopMenuOptions.Add
                (
                    new TopMenuOptions
                    {
                        Icon = "\ue60a",
                        MenuName = "查看位异或码",
                        Command = CmdBitwiseXorTool
                    }
                );
            }); 
        }

        //  文本链接触发
        private void HyperLinkFactory(object? param)
        {
            if (param is HyperlinkBack BackInfo)
            {
                if (BackInfo.LinkType == HyperlinkBackType.OpenRegexpTool)
                {
                    if (BackInfo.BindingData is not null and RegexpTestTool.InfoPakage _InfoPakage)
                    {
                        ActivityServer.RegexpTestToolUIShow(_InfoPakage);
                    }
                }
                else if (BackInfo.LinkType == HyperlinkBackType.OpenBitwiseTool)
                {
                    if (BackInfo.BindingData is not null and string _Content)
                    {
                        ActivityServer.BitwiseXorToolUIShow(_Content);
                    }
                }
                else if (BackInfo.LinkType == HyperlinkBackType.VisibleContentPopup)
                {
                    if (BackInfo.BindingData is not null and EnjoyContentPopue.InfoPakage _InfoPakage)
                    {
                        ActivityServer.ContentPopupToolUIShow(_InfoPakage);
                    }
                }
                else if (BackInfo.LinkType == HyperlinkBackType.MesDataBindingFace)
                {
                    if (!VarbinVsstMesMap) MesMapOpenEvent(null);
                }
                else if (BackInfo.LinkType == HyperlinkBackType.MesHttpRequest)
                {
                    if (BackInfo.BindingData is not null and List<object> _InfoPakage &&
                        _InfoPakage.Count == 2 &&
                        _InfoPakage.ElementAt(0) is KvpGroup _struct)
                    {
                        MesHttpSend(_struct, _InfoPakage.ElementAt(1));
                    }
                }
            }
        }

        //  Mes接口访问
        private async void MesHttpSend(KvpGroup _struct, object message)
        {
            Action? SendAction = await CustomMessageBox.Show(
                                new CustomMessageBox.InquiryDlPopupSetting
                                {
                                    Msg_Title = "MES消息",
                                    Msg_BodyText = "正在发送MES消息...",
                                    Msg_Result = 1
                                });

            if (message is not null and ActivityDetetorSuccess success &&
                _struct.SHowyDatas.Count >= 4)
            {
                string bingdingContent = _struct.SHowyDatas.ElementAt(3).Content;

                if (bingdingContent == "IMEI")
                {
                    HoldMesargGroups.Barcodes = success.IMEI;
                }
                else if (bingdingContent == "IMEI+QRCODE")
                {
                    HoldMesargGroups.BindingInfo = $"(IMEI={success.IMEI})";
                }

                Logger.Print(RuntimeLog.LogType.Debug, $"test bingding data {bingdingContent}");

                HoldMesargGroups.TestInfo = success.TestSteps;

                await HttpRequest();

                async Task HttpRequest()
                {
                    MesResportServer.Response? Response = await HoldMesResportServer.HttpRequest(HoldMesargGroups, MesargPushUrl);

                    Logger.Print(RuntimeLog.LogType.Debug, "mes response back");

                    if (Response is not null && Response.status == 0)
                    {
                        SendAction?.Invoke();
                        await CustomMessageBox.Show(
                            new CustomMessageBox.InquiryDlPopupSetting
                            {
                                Msg_Title = $"{HoldActivitySectionModel.ProductSelectedValuePair.Item1} - {HoldActivitySectionModel.ProductSelectedValuePair.Item2}",
                                Msg_BodyText = $"MES 报告成功",
                                Msg_Result = 2,
                                Msg_DelayExitTime = 2500
                            });
                    }
                    else
                    {
                        SendAction?.Invoke();
                        CustomMessageBox.InquiryPopupInvoke invoke = await CustomMessageBox.Show(
                            new CustomMessageBox.InquiryNmPopupSetting
                            {
                                Msg_WinWidth = 400,
                                Msg_WinHeight = 230,
                                Msg_Title = "MES报告发送失败",
                                Msg_InquiryIcon = 1,
                                Msg_BodyText = $"详情: {Response?.info}",
                                Msg_InquiryButtoms = ["重试", "知道了"]
                            });
                        if (invoke.index == 0)
                        {
                            await HttpRequest();
                        }
                    }
                }
            }
        }

        //  文本框聚焦
        private void FocusAndClearing()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                HoldArgumentOptions.Clearning(null);
                HoldDesertedOptions.DoImeiFocusTextBox = true;
                propertyChangeSend(nameof(HoldDesertedOptions));
                propertyChangeSend(nameof(HoldArgumentOptions));

            });
        }
    }
}
